【问题标题】:Are controllers mandatory for writing directives控制器是否必须编写指令
【发布时间】:2016-02-20 12:29:01
【问题描述】:

我只是 Angular 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>  

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

【问题讨论】:

  • 错误是什么?我认为通常模板需要是元素的文本表示——而不是文本节点。把模板改成'&lt;div&gt;helloWorld&lt;/div&gt;'能用吗?
  • @mgilson 未捕获错误:[$injector:modulerr]
  • 您能否尝试将脚本标签中的“angular.min.js”替换为“ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js”,看看它是否在您的本地工作?
  • @NitinGarg 链接不起作用
  • 请在 ajax.google 之前添加 http://...

标签: angularjs angularjs-directive


【解决方案1】:

不,您不需要控制器,但您的模板需要是实际的 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 课程并阐明了关键概念。

【讨论】:

  • 虽然我改变了它,我仍然得到模块错误。我认为这不是错误的原因。
  • 本地环境。贝内特Angular 加载正常。
  • 更新了 plunk。除非您还 include a reference to jquery,否则您不能使用内联脚本标签。您可以将应用声明和指令拉入单独的脚本并引用它,或者添加 jquery 脚本。
猜你喜欢
  • 2011-12-30
  • 2020-12-08
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多