2015-08-15 104 views
1

我試圖獲得一個自定義指令工作在角度,部分遵循official document自定義指令演示

在Chrome中,我只看到一個空白頁。

F12顯示了這個錯誤:

XMLHttpRequest cannot load file:///home/jeff/workspace/angularjs-intro/playground/my-customer.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. 

這是我走到這一步:

(function() { 
 

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

 
    app.controller('Controller', function() { 
 

 
    }); 
 

 
    app.directive('myCustomer', function() { 
 
     return { 
 
     restrict: 'E', 
 
     templateUrl: 'my-customer.html' 
 
     }; 
 
    }); 
 
    })();
<!doctype html> 
 
<html lang="en"> 
 

 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Example - example-example14-production</title> 
 

 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script> 
 
    <script src="script.js"></script> 
 

 
</head> 
 

 
<body ng-app="docsRestrictDirective"> 
 
    <div ng-controller="Controller"> 
 
    <my-customer></my-customer> 
 
    </div> 
 
</body> 
 

 
</html>

而且我-customer.html

Name: {{customer.name}} Address: {{customer.address}} 

任何幫助表示讚賞。

+0

您需要周圍的我的customer.HTML一個div。我也沒有看到任何數據被傳遞給指令。 – iamrelos

+0

在服務器上運行您的代碼。它正在拋出異源請求錯誤。 –

+0

我已經回答。這有助於你理解問題並推薦解決方案嗎? –

回答

1

這是我如何得到它的工作:

的script.js:( 「數據被傳遞給指令」)

app.controller('Controller', function() { 
    this.customer = { 
     name: 'Alice', 
     address: '123 Main Street', 
    }; 
}); 

的test.html

<div ng-controller="Controller as ctrl"> 
<my-customer></my-customer> 

請注意,必須使用別名as ctrl

變化我-customer.html至:(使用該資料控制器)

Name: {{ctrl.customer.name}} Address: {{ctrl.customer.address}} 
1

您應該在某些服務器上運行您的代碼,就好像您在沒有服務器的情況下運行一樣,瀏覽器會嘗試加載頁面,但url不是同一個域。因此你得到了明確的錯誤。

閱讀CORS

Cross-site HTTP requests initiated from within scripts have been subject to well-known restrictions, for well-understood security reasons. For example HTTP Requests made using the XMLHttpRequest object were subject to the same-origin policy. In particular, this meant that a web application using XMLHttpRequest could only make HTTP requests to the domain it was loaded from, and not to other domains. Developers expressed the desire to safely evolve capabilities such as XMLHttpRequest to make cross-site requests, for better, safer mash-ups within web applications.

注:有辦法禁用安全的Chrome,但不推薦的方式。

+0

感謝您的回答。我最終爲我的本地開發使用[disable-security](http://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome)。 –

+0

我遇到了禁用安全模式中的其他問題,所以我決定使用[python -m SimpleHTTPServer 80](http://askubuntu.com/questions/377389/how-to-easily-start-a- webserver-in-any-folder)啓動服務器。問題就消失了。 –