2015-08-15 6 views
1

Я пытаюсь получить пользовательскую директиву, работающую в угловом, частично следуя official document.demo пользовательской директивы

В 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

Вам нужен DIV, окружающий мой-customer.HTML. также я не вижу, чтобы данные передавались в директиву. – 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.

Примечание: Есть способы отключения-безопасности в хроме, но не рекомендуемый способ.

+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) для запуска сервера. и проблема уходит. –

Смежные вопросы