Angularjs directive: Isolated scope and attrs
请看这里的例子
1 2 3 4 5 6 7 8 9 10 11 12 13 | foodMeApp.directive('fmRating', function() { return { restrict: 'E', scope: { symbol: '@', max: '@', readonly: '@' }, require: 'ngModel', link: function(scope, element, attrs, ngModel) { attrs.max = scope.max = parseInt(scope.max || 5, 10); ... |
Angular需要在隔离作用域对象中定义
它在这里使用
那么,
为什么要像
因为这个应用程序是由Angular的作者编写的,我想是有原因的。
谢谢。
what is the purpose of attrs?
在与指令相同的元素上定义的属性有几个用途:
Can't one access all the attributes passed through attrs?
是的,你可以,但是
Why can't one access value of max as attrs.max instead of scope.max
以上回答
Why assign back like attrs.max = scope.max ?
我能想到这样做的唯一原因是,如果其他指令需要看到这个属性/值(即,指令间通信)。但是,另一个指令需要在该指令之后运行才能工作(可以通过
摘要:在带有隔离作用域的指令中,通常不希望使用
使用attrs,您可以访问在HTML标记中定义的属性,例如
1 | <fm-rating ng-model="$parent.restaurant.price" symbol="$" readonly="true"> |
因此,在本例中,您将可以访问符号和只读属性。您在自定义指令中定义的每个属性都将可用于ATTRS变量。
街区:
1 | attrs.max = scope.max = parseInt(scope.max || 5, 10); |
将分析并将当前scope.max值或5(如果不存在)分配给scope.max和attrs.max。这样,在分配之后,可以从attrs.max.中读取未定义的attrs.max属性。
检查fmtrating.js源,我不知道为什么/在哪里/何时使用这段代码。