Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Directive not working with templateUrl

Tags:

angularjs

New to angular and I've been having trouble with what should be a simple directive for the past hour or so. Would really appreciate some help!

I believe hello should appear, can't seem to get it to work?

test.html

   <html>
   <head lang="en">
     <title>Test</title>
   </head>
   <body>
    <div ng-app="myApp">
        <hello></hello>
    </div>


    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
    </body>
  </html>

main.js

    var myApp = angular.module('myApp', []);
    myApp.directive("hello", function() {
     return {
        restrict: 'E'
        templateUrl:"hello.html"
      };
    })`

hello.html

<p>Hello</p>
like image 554
user3821516 Avatar asked Nov 28 '22 01:11

user3821516


2 Answers

If you are testing locally and using Google Chrome then this will not work because AngularJS is making an Ajax call to these html files, but Chrome blocks this with the error:

XMLHttpRequest cannot load file:///[filepath...] Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

You can verify this by opening up your developer console and viewing the errors.

To get around this a couple ways:

  1. You can create a simple web server to run your code. If you have python you can just run the command (EDIT: from your folder containing index.html):

    python -m SimpleHTTPServer

  2. You can disable same origin policy in Chrome: https://stackoverflow.com/a/6083677/1100379

  3. Use an Chrome extension which may do this for you. I looked one up and this was the first result: Allow-Control-Allow-Origin

like image 162
Asher Garland Avatar answered Dec 16 '22 06:12

Asher Garland


Everything works fine, just make sure your syntax is correct. Do not miss comma's in JSON

myApp.directive("hello", function() {
  return {
    restrict: 'E',
                 ^
    templateUrl:"hello.html"
  };
})

Demo: http://plnkr.co/edit/Z6rjbsuqzmcD4gBem36c

like image 45
Raghavendra Avatar answered Dec 16 '22 06:12

Raghavendra