我如何通过多个属性到Angular.js属性的指令? [英] How do I pass multiple attributes into an Angular.js attribute directive?
问题描述
我有一个属性指令的限制如下:
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.
如果该指令是一个element指令,以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()
}
};
});
<大骨节病> 小提琴 骨节病>
如果属性的值例如数
将硬$ C $的CD,我建议使用的$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).
这篇关于我如何通过多个属性到Angular.js属性的指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!