0

I'm just a beginner in angular JS. I'm learning to a write a directive.

<!DOCTYPE>
<html ng-app="myapp">
<head>
<script src="angular.min.js"/>
<script>
var app = angular.module('myapp', []);

app.directive('helloWorld',function()
{
return{
restrict: 'AEC',
replace: 'true',
template: '<h1>helloWorld</h1>' 
}
});
</script>
</head>
<body>
    <h1>Hello World example</h1>
<hello-world></hello-world>
</body>
</html>  

Now, what is wrong in the above code, I get an error - Uncaught Error: [$injector:modulerr].
1. Is controller mandatory to write a directive, does it not inherit from $rootscope.
2. How can I master directives.

user3004356
  • 870
  • 4
  • 16
  • 49

1 Answers1

0

No, you don't need a controller, but your template needs to be actual html, since you have set replace: true in your directive. You can either fix that:

template: '<h1>helloWorld</h1>' 

...or take out replace: true, and your directive works. See this previous SO answer on what's happening with replace.

See this plunker adapted from your code.

There are a ton of great resources online to learn about directives, but the best one I have found is this Udemy course by Dan Wahlin. It's worth the price, especially if you catch the reduced-rate offers. He also wrote an excellent series of blog posts that mirrors the Udemy course and illuminates the key concepts.

Community
  • 1
  • 1
Bennett Adams
  • 1,808
  • 14
  • 17
  • Well though I change that, I still get the module error. I don't think that can be areason for the error. – user3004356 Feb 20 '16 at 04:12
  • local env. benett. Angular is loading fine. – user3004356 Feb 20 '16 at 04:19
  • Updated the plunk. You cannot use inline script tags unless you also [include a reference to jquery](http://stackoverflow.com/questions/21336350/angularjs-inline-script-in-the-included-html-template). You can either pull the app declaration and directive into a separate script and refer to that, or add the jquery script. – Bennett Adams Feb 20 '16 at 04:23