AngularJS - How to access an array inside nested ng-repeat

I have a recursive array in js:

[{ type: 'cond', conditionId: 1, conditions: undefined }, { type: 'cond', conditionId: 2, conditions: undefined }, { type: 'group', conditionId: undefined, conditions: [{ type: 'cond', conditionId: 3, conditions: undefined }, { type: 'cond', conditionId: 4, conditions: undefined }] }] 

It is displayed in AngularJS using ng-repeat recursively with an inline template:

 <script type="text/ng-template" id="recursive_template.html"> <div> some logic </div> <div ng-repeat="cond in cond.conditions" ng-include="'recursive_template.html'"></div> <div> some more logic </div> </script> <div ng-controller="EditRulesController"> <div ng-repeat="cond in conditions" ng-include="'recursive_template.html'" class="row"> </div> </div> 

Everything works perfectly. Now I want to remove one element from internal ng-repeat. I can get the index of the element that I click (for deletion) using $ index , as well as the cond object as a parameter on ng-click. I can also access $ parent , but it points to the root of the object ...

How to access an internal array without manually searching the entire array of conditions recursively? It is strange that you can easily access the index of the internal array, but not the actual instance of the array.

And any advice on this? Thanks..

EDIT 03/21/2016

Before the accepted answer, the version of "brute force" is implemented as follows:

  $scope.deleteConditionClick = function (id) { deleteCondition($scope.conditions, id); }; function deleteCondition(conditions, id) { var conds = conditions; if (conds) { for (var i = 0; i < conds.length; i++) { if (conds[i].type === 'cond') { if (conds[i].conditionId === id) { conds.splice(i, 1); return true; } } else if (conds[i].type === 'group') { deleteCondition(conds[i].conditions, id); } } } } 

I hope this helps others with a similar problem.

+5
source share
3 answers

Have you tried setting the delete action to be ng-click="cond=undefined" ? This will delete the remote state. Then you can use ng-show / ng-if to control visibility in the view.

+2
source

This is how I grab items with multiple indexes:

 <div ng-repeat="x in outerArray" ng-init="outerIndex = $index"> <div ng-repeat="y in innerArray"> {{ innerArray[outerIndex] }} </div> </div> 

I think this is what you asked? Hope this helps.

+1
source

You can pass the parent array and object as parameters (for example: ng-click="delete(conditions, cond) ") and use the .indexOf() function to find the index of the object (for example, $scope.delete = function(conditions, cond){index = conditions.indexOf(cond)...} )

0
source

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


All Articles