Reputation: 216
While studying about directives, I keep getting something basic wrong because I simply cannot make one work in order to import something from another html file.
HTML (index.html
)
<!DOCTYPE html>
<html ng-app="myapp">
<head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script><script type="text/javascript" src="app.js"></script></head>
<body>
<hello-world></hello-world>
</body></html>
HTML (ssth.html
- in the same directory as index.html
):
<h3>hello world</h3>
JavaScript (app.js - same dir)
(function(){
var app = angular.module('myapp', []);
app.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: 'true',
templateUrl: "ssth.html",
};
});
})();
Yet my browser simply won't show the hello word
message to me. I know there's something basic I'm missing but what?
Error reports from chrome console:
XMLHttpRequest cannot load file:///.../ssth.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///.../ssth.html'.
Error: [$compile:tpload] http://errors.angularjs.org/1.3.14/$compile/tpload?p0=ssth.html
Upvotes: 2
Views: 1687
Reputation: 136144
You should host you code on some server so that the template gets accessible, Because the template url which directive is going to load should have //http
protocol.
What happens when it uses //file
protocol?
While fetching that template by angular it uses $templateRequest
to fetch the template, & $templateRequest
API uses $http
method to fetch the templates, and if you made any ajax call with //file
protocol that going to fail anyhow. So by hosting your code folder on some server like WAMP, IIS, etc. will fix your issue.
Work Around(if you fix it without hosting code)
Other possible quick solution would be use template
option instead of templateUrl
like template: "<h3>hello world</h3>"
but that would be not a better way to fix it. :)
Upvotes: 2
Reputation: 39
Please check this link: http://plnkr.co/edit/e3w54TZEmfj8h5O6BX7B?p=preview,
I solved your problem in above link.
I add <hello-world></hello-world>
in index.html and
in script.js file, i add
gitHubViewer.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: 'true',
templateUrl: "ssth.html",
};
});
Please review it.
Upvotes: 0
Reputation: 11
Have you added your directive script in your index.html?
<script src="{path}/helloWorld.js"></script>
Upvotes: -1