Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "ng-repeat" within template of a directive in Angular JS?

I'm new to Angular JS and I am trying to create a custom directive that will be used as below:

<div linkedlist listcolumns="{{cashAccountsColumns}}"></div>

Corrps. controller will be:

$scope.cashAccountsColumns = [   {"field": "description", "title": "Description"},   {"field": "owner", "title":"Owner"},   {"field": "currentBalance", "title":"Current Balance" } ]; 

And the directive code is:

return {       restrict : 'EA',       transclude : false,       templateUrl : 'html/linkedlist.html',       scope: {          listcolumns: "@"       },       link : function(scope, element, attrs) {       } } 

template is:

<table class="box-table" width="100%">   <thead>     <tr>       <th scope="col" ng-repeat="column in listcolumns">         {{column.title}}       </th>     </tr>   </thead> </table> 

But this is not working. I'm not getting the value of column.title on screen instead too many rows as below are added to DOM:

<th ng-repeat="column in listcolumns" scope="col" class="ng-scope ng-binding"></th> 
like image 718
user2401127 Avatar asked May 20 '13 09:05

user2401127


People also ask

What is Ng-repeat directive in AngularJS?

AngularJS ng-repeat Directive The 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.

Does ng-repeat create a new scope?

Directives that Create Scopes In most cases, directives and scopes interact but do not create new instances of scope. However, some directives, such as ng-controller and ng-repeat, create new child scopes and attach the child scope to the corresponding DOM element.

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.

What is the difference between ng-repeat and ngFor?

ng-repeat created inherited child scope for each element of collection, while *ngFor creates local variable in the that block.


1 Answers

Passing an entire object with attribute will not work, you have to use dual way binding. Just change binding from @ to = and modify the HTML below to make it work:

changes to directive code:

// ... scope: {     listcolumns: "=" }, // ... 

changes to template:

  <div linkedlist listcolumns="cashAccountsColumns"></div> 
like image 171
Ajay Beniwal Avatar answered Oct 02 '22 14:10

Ajay Beniwal