21

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 }];
}
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
iLemming
  • 34,477
  • 60
  • 195
  • 309

3 Answers3

26

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>'
}
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 1
    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 – bsr Aug 23 '13 at 12:17
  • 1
    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. – PhiLho May 07 '15 at 10:15
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 '@'
   }
}
3

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

Community
  • 1
  • 1
Guntram
  • 961
  • 14
  • 19