Angular 1.X控制器和指令之间是什么关系 [英] What is the relationship between an Angular 1.X controller and directive
问题描述
我不是问这两者之间有什么区别,我想知道当组件既有指令又有控制器时它们如何协同工作.
I am NOT asking what the difference between the two is, I'm wondering how they work together when there is both a directive and controller for a component.
推荐答案
我不确定为什么您对此一票否定,因为我认为这是与angular 1不太清晰的方面之一有关的问题.x.
使用控制器设置指令的主要原因之一是将指令的API公开给其他指令.一个很好的例子是 ngModel
和 ngModelController
.许多自定义指令都需要访问 ngModel
,该代码也在自定义指令所在的位置或上方声明.您可以通过以下指令在指令定义中看到这一点:
One of the prime reasons to set up a directive with a controller is to expose a directive's API to other directives. A good example of this is ngModel
and the ngModelController
. Many custom directives need access to the ngModel
that's also declared on or above where the custom directive is declared. You see this in the directive definition via:
{ require:'^ngModel' }
这实际上是说 this 自定义指令需要访问 ngModelController
上可用的API才能执行其他工作.例如,您希望指令对特定的ngModel进行一些自定义解析或格式化.在我的应用程序中,我不断收到来自服务器的日期字符串错误.我创建了这个自定义指令来处理错误并正确设置字符串格式(这是coffeescript btw):
This is actually saying this custom directive needs to access the APIs available on the ngModelController
to do additional work. For instance, you want a directive to do some custom parsing or formatting on a particular ngModel. In my app, I kept getting errors for date strings that came back from the server. I created this custom directive to handle the error and format the string properly (this is coffeescript btw):
.directive 'dateString', [
()->
{
priority: 10
require: 'ngModel'
link: ($scope, elem, attrs, ngModel)->
ngModel.$formatters.push (val)-> new Date(val)
}
]
如果没有 ngModelController
,我将无权访问API以添加新的格式化程序功能.
If there were no ngModelController
, I would not have access to the APIs to add a new formatter function.
因此,总而言之,我们可以创建指令控制器以为可能在同一UI元素上运行的其他指令提供API.
So in conclusion, we might create directive controllers to provide APIs for other directives that may operate on the same UI element.
为了符合Angular的精神和意图,使用控制器向模板公开API优于尝试使用jquery实现.换句话说,最好这样做:
In order to be within the spirit and intent of Angular, using a controller to expose APIs to the template is better than trying to use a jquery implementation. In other words, it's better to do this:
指令w.控制器
controller: function($scope){
$scope.doSomething = function(){ ... }
},
template: '<div><button ng-click="doSomething()">Click Me</button></div>'
与这样的事情
指令w.类似于jQuery的实现
link: function($scope, elem, attrs){
elem('button').bind('click', function(){ ... })
},
template: '<div><button>Click Me</button></div>'
这篇关于Angular 1.X控制器和指令之间是什么关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!