angularjs – 控制器与指令之间的区别和何时使用?

前端之家收集整理的这篇文章主要介绍了angularjs – 控制器与指令之间的区别和何时使用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很难理解控制器的用途是什么.我知道这是你引用的东西,但是因为你可以将它放在一个指令中,是否有一种情况你需要在你的html中使用ng-controller来代替特定部分,而不是创建一个内置控制器的指令在?

解决方法

is there ever a scenario where you would want to use ng-controller for a specific section in your html rather than creating a directive that has a controller built in?

是的,绝对是的.

>当目标是操纵DOM时使用指令.
>如果要创建可重用组件,请使用指令.
>当您需要将值绑定到DOM时,请使用控制器.

对于这两种方法中的任何一种,可能还有其他一百种情况,但我相信这应该足以证明一种方法的使用是合理的.

至于两者之间的差异,请看@yvesmancera已经指出的问题(angularjs-directives-vs-controllers).

In Angular,a Controller is defined by a JavaScript constructor function that is used to augment the Angular Scope.

When a Controller is attached to the DOM via the ng-controller directive,Angular will instantiate a new Controller object,using the specified Controller’s constructor function. A new child scope will be created and made available as an injectable parameter to the Controller’s constructor function as $scope.

At a high level,directives are markers on a DOM element (such as an attribute,element name,comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.

猜你在找的Angularjs相关文章