Ng-repeat for accessing an array inside objects

I have an array with a list of objects. Each object also contains an array (see below). I use ng-repeat to iterate over a child array for each object, I tried many different ways, but it just doesn't work at all. Any hint, direction, help would be greatly appreciated. Thanks.: -)

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script> <script> angular.module('mlApp', []) .controller('mlCtrl', [function () { var self = this; self.contacts = [ { contact: 'AAA', mlist: [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1] }, { contact: 'BBB', mlist: [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1,1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] } ]; } ]); <div ng-app="mlApp" ng-controller="mlCtrl as mCtrl"> <table> <thead>..</thead> <tbody> <tr ng-repeat="p in mCtrl.contacts"> <th width="100px" >{{p.contact}}</th> <td ng-repeat="c1 in p.mlist"><input type="checkbox" ng-check='{{c1}}' /></td> </tr> </tbody> </table> </div> 
+5
source share
2 answers

Hint - checking the console for errors - Angular is (usually) very useful with such things.

You have duplicate values ​​in the array you use in the internal ng repeat, so you need to track it. In this example, I used $ index:

 angular.module('mlApp', []) .controller('mlCtrl', [ function() { var self = this; self.contacts = [{ contact: 'AAA', mlist: [1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1] }, { contact: 'BBB', mlist: [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1] } ]; } ]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="mlApp" ng-controller="mlCtrl as mCtrl"> <table> <thead>..</thead> <tbody> <tr ng-repeat="p in mCtrl.contacts"> <th width="100px">{{p.contact}}</th> <td ng-repeat="c1 in p.mlist track by $index"> <input type="checkbox" ng-check='{{c1}}' /> </td> </tr> </tbody> </table> </div> 
+11
source

You can do the same:

 var myApp = angular.module('myApp',[]); myApp.controller('mycontroller',['$scope',function($scope){ $scope.students=[]; var i=0; for(i=0;i<5;i++){ var item={Name:'',Marks:[]}; item.Name='student' + i; item.Marks.push({Maths:50-i,Science:50 +i}); $scope.students.push(item); } }]); 
 <html ng-app='myApp'> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script> </head> <body ng-controller='mycontroller'> <div ng-repeat='student in students'> Name : {{student.Name}} <span ng-repeat="m in student.Marks">Maths:{{m.Maths}} Science:{{m.Science}}</span> </div> </body> </html> 
0
source

Source: https://habr.com/ru/post/1211664/


All Articles