The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.
Template:
<div example-directive example-number="99" example-function="exampleCallback()"></div>
Directive:
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()
}
};
});
fiddle
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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…