0

I am creating a dynamic table row with an input fields. In angular we can access the index of array by using this $index variable. Now my problem is I have a sublevels array and I need to get the index of the parent array. And every row has a remove button. And I need to access the parent index ID for accessing.

Here's the sample object value:

Object
    items: Array [2]
        0: Object
            particular_name: "SAMPLE PARTICULAR TITLE"
            child_label: Object
            items: Array [3]
                0: Object
                1: Object
                2: Object
            $$hashKey: "object:13"
        1: Object
            particular_name: "SAMPLE PARTICULAR TITLE"
            child_label: Object
            items: Array [0]
            $$hashKey: "object:41"

In my template I have this:

<!-- this is the parent array -->
<div ng-repeat="item in quoteHeader.items" class="row">
    <!-- some codes here... -->
    <!-- 2nd level array -->
    <tr ng-repeat="item in quoteHeader.items[$index].child_label.items">
    <!-- need to access the parent index ID here... But index ID here is the index of the 2nd level array-->
       <button type="button" class="btn btn-danger" ng-click="removeParent($index)"><span class="fa fa-times"></span></button>

JS:

 $scope.removeParent = function($index) {   
        console.log($index);
        //$scope.quoteHeader.items[$index].splice($index, 1);           
    }

1 Answer 1

2

Each ng-repeat creates a child scope with the passed data. You need to get the parent index in child data by using $parent. Like

<button type="button" class="btn btn-danger" ng-click="removeParent($parent.$index)"><span class="fa fa-times"></span></button>

Another way to use ng-init directive. Just see an example

<div ng-repeat="item in quoteHeader.items" class="row" ng-init="parentIndex = $index">
    <!-- some codes here... -->
    <!-- 2nd level array -->
    <tr ng-repeat="item in quoteHeader.items[$index].child_label.items">
    <!-- need to access the parent index ID here... But index ID here is the index of the 2nd level array-->
       <button type="button" class="btn btn-danger" ng-click="removeParent(parentIndex)"><span class="fa fa-times"></span></button>
Sign up to request clarification or add additional context in comments.

2 Comments

Is it applicable in multiple sublevels?
Yes. in that case you need to call removeParent($parent.$parent.$index) to the depth of your object or array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.