Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 }]; } 
like image 401
iLemming Avatar asked Feb 02 '13 01:02

iLemming


People also ask

Does ng-repeat create a new scope?

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.

How do you use NG-repeat in a table?

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.

How do I get an index value in ng-repeat?

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.

Where is the last element in NG-repeat?

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 .


2 Answers

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>' } 
like image 103
Mark Rajcok Avatar answered Oct 21 '22 07:10

Mark Rajcok


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 '@'    } } 
like image 29
Maximiliam Nahlén Avatar answered Oct 21 '22 06:10

Maximiliam Nahlén