Pedr Pedr - 3 months ago 23
Javascript Question

How do I pass multiple attributes into an Angular.js attribute directive?

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

If the directive was an element directive, restricted with
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?


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);
            scope.callback();  // calls exampleCallback()


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