Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  150] [ 3]  / answers: 1 / hits: 120791  / 11 Years ago, tue, may 14, 2013, 12:00:00

I have an attribute directive restricted as follows:



 restrict: A


I need to pass in two attributes; a number and a function/callback, accessing them within the directive using the attrs object.



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.



How do I pass multiple attributes into an attribute directive?


More From » parameters

 Answers
812

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).


[#78238] Monday, May 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;