Lar*_*ish 7 angularjs angularjs-directive
所以我已经使用AngularJS几个月了,我已经在互联网和我的AngularJS指令书中搜索了这个答案.
在指令中,我几乎总是看到这段代码:
link: function(scope, element, attrs) {
//body
}
Run Code Online (Sandbox Code Playgroud)
函数"scope,element,attrs"中的项目究竟是什么?这可能是一个愚蠢的问题,但我似乎无法在任何地方找到答案.
谢谢!
Ton*_*yGW 12
参数scope,, element和attrs是根据此处的文档为您的自定义指令定义的,但您可以将它们重命名为您的类似.
scope:这是自定义指令的范围,类似于$scope控制器中的范围
element:这是自定义指令的元素
attrs:这是自定义指令中的属性集.(应该是元素的属性,感谢@zeroflagL进行更正!)
例如,如果你构建一个名为的自定义指令myDirective,你可能会在你的html部分中使用它,如下所示:
<my-directive num-rows="3"></my-directive>
Run Code Online (Sandbox Code Playgroud)
这里num-rows是你的指令的属性,你可以在你的link函数中获得它的值:
function link(scope, element, attrs) {
console.log('num-rows:', attrs.numRows);
//you can change its value, too
attrs.$set('numRows', '10'); //attrs setter
//you can watch for its changes to trigger some event
attrs.$observe('numRows', function(newVal) {
console.log('trigger some event for the changes in numRows here');
});
}
Run Code Online (Sandbox Code Playgroud)
此外,在上面的链接函数中,您可以将元素/指令绑定到操作:
element.bind('click', function() {
console.log('do something with the click event');
});
Run Code Online (Sandbox Code Playgroud)
我建议你花些时间阅读文档.链接函数可以采用第4个参数,该参数是自定义指令中所需的另一个指令的控制器.例如:
require: '^ngModel'
....
function link(scope, element, attrs, ngModelCtrl) {
....
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12113 次 |
| 最近记录: |