Last Updated: February 25, 2016
·
15.65K
· pomodoro

Angular.js: passing reference to directive

When first using the linking function on a directive I expected attribute values to be available through the attrs argument.

Turns out when you want to pass a reference from the parent scope you need to use the scope attribute in the directive definition object.

<pre ng-app="app" ng-controller="TestCtrl">
    controller: <span ng-bind="user.username"></span>
    directive: <span my-user="user"></span>
</pre>

var app = angular.module('app', []);

app.controller('TestCtrl', function($scope) {
    $scope.user = { username: 'Ben' };
});

app.directive('myUser', function() {
    return {
        template:
            '<span ng-bind="user.username"></span>',
        scope: { user: '=myUser' },
        link: function(scope, element, attrs) {
            /*
             *  returns: 'user'
             *    attrs.myUser is just the string, you
             *    should use scope on the directive
             *    definition object
             */
            console.log(attrs.myUser);

            // returns: 'Ben'
            console.log(scope.user.username);
        }
    };
});

2 Responses
Add your response

You have to assign the scope to accept an object by adding in your return object scope: { user: '=myUser'
}
default seems to only accept strings.

over 1 year ago ·

How can i pass this to a function in angularjs. I have multiple select objects with the same ng-model. i want to pass the selected element to the ng-change function when an element is selcted from the list

over 1 year ago ·