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 }]; }
The controller creates a child scope and the ng-repeat , which will create an LI element for each item in the list of To Do items. It also creates a new scope for each element.
Definition and UsageThe ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.
You can use $last variable within ng-repeat directive. Take a look at doc. Where computeCssClass is function of controller which takes sole argument and returns 'last' or null .
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>' }
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 '@' } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With