如何将多个属性传递给 Angular.js 属性指令?
我有一个属性指令限制如下:
I have an attribute directive restricted as follows:
restrict: "A"
我需要传入两个属性;一个数字和一个函数/回调,使用 attrs
对象在指令中访问它们.
I need to pass in two attributes; a number and a function/callback, accessing them within the directive using the attrs
object.
如果指令是元素指令,受 "E"
限制,我可以这样做:
If the directive was an element directive, restricted with "E"
I could to this:
<example-directive example-number="99" example-function="exampleCallback()">
但是,由于我不会深入讨论的原因,我需要将指令设为属性指令.
However, for reasons I won't go into I need the directive to be an attribute directive.
如何将多个属性传递到属性指令中?
指令可以访问在同一元素上定义的任何属性,即使指令本身不是元素.
The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.
模板:
<div example-directive example-number="99" example-function="exampleCallback()"></div>
指令:
app.directive('exampleDirective ', function () {
return {
restrict: 'A', // 'A' is the default, so you could remove this line
scope: {
callback : '&exampleFunction',
},
link: function (scope, element, attrs) {
var num = scope.$eval(attrs.exampleNumber);
console.log('number=',num);
scope.callback(); // calls exampleCallback()
}
};
});
如果属性 example-number
的值是硬编码的,我建议使用 $eval
一次,并存储值.变量 num
将具有正确的类型(数字).
If the value of attribute example-number
will be hard-coded, I suggest using $eval
once, and storing the value. Variable num
will have the correct type (a number).