控制器是否必须用于编写指令

时间:2016-02-20 04:02:50

标签: angularjs angularjs-directive

我只是角度JS的初学者。我正在学习写一个指令。

<!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>  

现在,上面的代码有什么问题,我收到错误 - 未捕获错误:[$ injector:modulerr]
1.控制器是否必须编写指令,是否不从$ rootscope继承 2.我如何掌握指令。

1 个答案:

答案 0 :(得分:0)

不,您不需要控制器,但您的模板需要是实际的html,因为您已在指令中设置了replace: true。你可以解决这个问题:

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

...或取出replace: true,你的指令有效。请参阅this previous SO answer了解replace发生的事情。

See this plunker adapted from your code

网上有很多很好的资源来了解指令,但我找到的最好的资源是this Udemy course by Dan Wahlin。这是值得的,特别是如果你赶上降价优惠。他还写了an excellent series of blog posts,反映了Udemy课程并阐明了关键概念。