Table from a 2D array in AngularJS

I was stuck on something that I expected when AngularJS worked out of the box without any problems, and oddly enough ...

I use the JSON service, which returns the data as a 2D array:

$scope.data= [ ["val-11", "val-12", "val-13"], ["val-21", "val-22", "val-23"] ]; 

From this, I am trying to create a table as follows:

 <table> <tr ng-repeat="row in data"> <td ng-repeat="col in row">{{col}}</td> </tr> </table> 

I do not understand why AngularJS does not cope with such a basic scenario. I can get the correct $ index for the parent loop, if I need it, I can iterate over the values, but with only one loop like this "col in data [0]", but I can’t get any result trying to use the nested as shown above.

Am I doing something wrong? It seems to be too simple not to work right away. Please help me with this strange problem.

+6
source share
1 answer

In Angular 1.0.x, the ng-repeat directive had many errors caused by trying to “guess” whether values ​​without an object (such as a string or number) were added, deleted, or moved. The problem is that non-objects do not have their own identity, so they cannot be accurately tracked. This was problematic in a number of cases, and also caused the ngRepeat code to be bloated with many workarounds and edge cases.

In 1.2, we improved the ng-repeat syntax so that the developer can specify exactly how to identify elements in the collection. This is done with the keyword "track by". One consequence of this is that we prohibit items that have the same identifier.

By default, ng-repeat will try to track the value of the element. If you have duplicate elements, such as the same object or identical lines or numbers, then ng-repeat will complain and you will see an error in the console.

 var TableCtrl = function($scope) { $scope.data= [ ["", "", "val-13"] ]; } 

Here, the first two elements in the submatrix represent the same “empty” row. See this script: http://jsfiddle.net/tEU8r/

If you really want to have duplicate elements in the collection, you need to provide the ng-repeat method to distinguish them. The simplest and most obvious approach is to track positions by their position in the collection. This is done using "track by $ index". Here is the same example, but fixed in this way:

 <table ng-controller="TableCtrl"> <tr ng-repeat="row in data"> <td ng-repeat="col in row track by $index"> {{$parent.$index}}-{{$index}} {{col}} </td> </tr> </table> 

http://jsfiddle.net/h44Z8/

So this is not a bug in AngularJS. But you are right that people should know about this change when upgrading to 1.2

+14
source

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


All Articles