2014-12-26 147 views
2

我試圖用AngularJS指令,這裏是我的代碼:AngularJS無法加載模板

的index.html

<!DOCTYPE html> 
<html lang="en" ng-app="myapp"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Directive</title> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.js"></script> 
    <script type="text/javascript" src="app.js"></script> 
</head> 
<body> 
    <photo photo-src="abc.jpg" caption="This is so Cool" /> 
</body> 
</html> 

app.js

var app = angular.module('myapp',[]); 

app.directive('photo',function(){ 
    return { 
     restrict: 'E', 
     templateUrl: 'photo.html', 
     replace: true, 
     scope: { 
      caption: '@', 
      photoSrc: '@' 
     } 
    } 
}); 

photo.html

<figure> 
    <img ng-src="{{photoSrc}}" width="500px"> 
    <figcaption>{{caption}}</figcaption> 
</figure> 

我測試的文件通過操作直接在瀏覽器上。它在Firefox上正常工作,但不在IE瀏覽器& chrome上。 IE & Chrome顯示錯誤Failed to load template

我該如何解決?

+0

看看網絡,看看它試圖從 – PSL

+0

加載什麼路徑@PSL它試圖加載的路徑是正確的。這是來自chrome的錯誤''錯誤:未能在'XMLHttpRequest'上執行'send':無法加載'file:/// E:/ www/lab/angularjs/directive/photo.html'。'' – user1995781

+1

ie因爲您正在嘗試使用文件協議加載。它沒有託管?您可能必須禁用安全性才能使其加載......所以缺少來源不是問題。 – PSL

回答

3

你應該從HTTP Web服務器調用它,或者你可以用一個腳本標籤寫的模板在同一個文件象下面這樣:

<script type="text/ng-template" id="/tpl.html"> 
    Content of the template. 
</script> 
0

其在Chrome的安全性問題。 Chrome不允許跨域請求。 啓動鑲邊 - 禁用網絡安全

在Windows上:

的chrome.exe - 禁用網絡安全

在Mac:

打開/應用/谷歌\ Chrome.app/ --args --disable-web-security

這將允許跨域請求。記住它會禁用網絡安全。

不用擔心,它將在您託管文件時起作用。