How do you access an ng-repeat item in a directive's scope?

19,081

Solution 1

If by "set the scope value" you mean have the template work, then

template: '<div>{{ p.name }}</div> <div>{{ p.age }}</div>'

Since each iteration of ng-repeat creates a new child scope, p is defined on that scope. Since your directive is not creating an isolate scope, you don't need attribute person, so this works with the above:

<my-element ng-repeat="p in people"></my-element>

If you want an isolate scope, use

<my-element ng-repeat="p in people" person='p'></my-element>

and

return {
   restrict: 'E',
   scope: {
       person: '='
   },
   template: '<div>{{ person.name }}</div> <div>{{ person.age }}</div>'
}

Solution 2

you do not need to create an isolated scope in the directive. ng repeat will do this automatically for you. so just remove:

in the directive:

scope: {
   person: '='
},

and in the ng repeat html markup:

person='p'

in your directive you will be able to access something like

$scope.p.personAttribute

like mentioned in the explanation here: angularjs-pass-instance-of-each-ng-repeat-in-html-to-directive

Solution 3

I like to use '@' when defining the directive scope. This enables the directive isolated scope to access p, for example in link:

return {
   scope: '@',
   link: function(scope) {
       console.log(scope.p); //It can now be accessed because of '@'
   }
}
Share:
19,081
iLemming
Author by

iLemming

Updated on June 20, 2022

Comments

  • iLemming
    iLemming about 2 years

    How do you set the scope value for something like this:

    <div ng-controller="MyCtrl">
          <my-element ng-repeat="p in people" person='p'></my-element>
    </div>
    
    var myApp = angular.module('myApp',[]);
    
    myApp.directive('myElement', function(){
        return {
            restrict: 'E',
            template: '<div>{{ name }}</div> <div>{{ age }}</div>'
        }
    });
    
    function MyCtrl($scope) {
        $scope.people = [{ name: 'Mike', age: 20 },{name: 'Peter', age: 22 }];
    }
    
  • bsr
    bsr almost 11 years
    is this form ng-repeat="p in people" person='p' still valid. I don't see it mentioned in the docs and give error for me. thanks
  • asologor
    asologor almost 10 years
    in your example it can be accessed without '@' too
  • PhiLho
    PhiLho about 9 years
    The first form is brittle, because it relies on the loop variable name, which is chosen by the user of the directive... The second form works well, thanks for sharing.