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

Viewed 2029

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 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 fine. Now I want to delete one item from inner ng-repeat. I can get the index of the item that I click on(to delete) with $index, also the object cond as parameter on ng-click. I can also access $parent but it points to the root of the object...

How to access the inner array without manually search through the whole conditions array recursively? Its strange that you can easily access the index of the inner array but not the actual array instance.

And any one advice on this issue? Thank you..

EDIT 21/03/2016

Before the accepted answer, the 'brute-force' version is implemented like this:

        $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 it will help others with similar problem.

3 Answers
Related