Last Updated: February 25, 2016
· 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>


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

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

app.directive('myUser', function() {
    return {
            '<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

            // returns: 'Ben'

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 ·