AngularJS: traversing nested arrays

后端 未结 2 1280
我寻月下人不归
我寻月下人不归 2021-02-06 15:06

I am working with a nested array with the structure...

$scope.items = [{attr1: val1, 
  attr2: val2,
  items: [{
     attr1: val1, 
     attr2: val2,
     items:         


        
2条回答
  •  既然无缘
    2021-02-06 15:26

    If you alias item.items in the ng-repeat expression, angular will keep track of the array structure and hierarchical relationships for you.

    Then, operations on the tree can simply pass in the item, the $index, or the array of items - without knowledge of the full array structure:

      
      
      
    

    js:

    $scope.addItem = function(item) {
      item.items.push({
        attr1: 'my new - attr1',
        attr2: 'my new - attr2',
        items: []
      });
    }
    $scope.addSiblingItem = function(items, position) {
      items.splice(position + 1, 0, {
        attr1: 'sibling - new attr1',
        attr2: 'sibling - new attr2',
        items: []
      });
    }
    $scope.deleteMe = function(items, position) {
      items.splice(position, 1);
    }
    

    To get the number of siblings, you can refer to items.length:

    Item #{{$index + 1}} of {{items.length}}


    If you really need to access the parent siblings from child items, you can add another alias for parent = item and add it to the item using ng-init:

    ng-repeat="item in items = (parent = item).items" ng-init="item.parent = parent"
    

    Then you have access to the grandparent (parent.parent) and its items (the parent siblings).

    In addition, you can keep track of the current nest level using ng-init:

    ng-init="item.parent = parent; item.level = parent.level + 1"
    

    Here is a working demo: http://plnkr.co/xKSwHAUdXcGZcwHTDmiv

提交回复
热议问题