2015-08-15 126 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)启动服务器。问题就消失了。 –