ng-repeat's element not updated on array modification

前端 未结 3 1591
既然无缘
既然无缘 2020-12-31 15:12

When I trying to update my array on ng-click in order to update my ng-repeat\'s directive items:

  • 相关标签:
    3条回答
    • 2020-12-31 15:16

      Have you tried changing the selectL2Menu function to:

      $scope.selectL2menu = function (itemL1name){
          $scope.mainMenuL2CurArr = $scope.mainMenuL2Obj[itemL1name];
      }
      
      0 讨论(0)
    • 2020-12-31 15:24

      Without seeing more of your controller code, it is difficult to determine what the problem might be. Here is a simplified working fiddle. I suggest you compare it to what you have.

      Note that you don't need to call $scope.$apply() because the ng-click directive will do that for us automatically.

      HTML:

      <ul>
          <li ng-repeat="itemL1 in mainMenuL1Arr" ng-click="selectL2menu(itemL1.name)">
            {{itemL1.name}}</li>
      </ul>
      <ul style="margin-left: 20px">
          <li ng-repeat="itemL2 in mainMenuL2CurArr"><a href="#">
               <span>{{itemL2.name}}</span>
          </a>
          </li>
      </ul>
      

      JavaScript:

      function MyCtrl($scope) {
          $scope.mainMenuL1Arr = [ {name: 'one'}, {name: 'two'} ];
          $scope.mainMenuL2Obj = { 
              one: [ {name: '1.1'}, {name: '1.2'} ],
              two: [ {name: '2.1'}, {name: '2.2'} ] };
          $scope.mainMenuL2CurArr = $scope.mainMenuL2Obj['one'];
          $scope.selectL2menu = function (itemL1name) {
              console.log(itemL1name);
              $scope.mainMenuL2CurArr = $scope.mainMenuL2Obj[itemL1name];
          };
      }
      
      0 讨论(0)
    • 2020-12-31 15:42

      Can you try to make the $scope.$apply() after you add item in array like

      $scope.array.push({id: 1, name: 'test'});
      $scope.$apply();
      

      Works fine for me, probably you have another function of a plugin or something like this, that blocking the scope apply, in my case I have a select2 and when select in field the apply is not fired

      0 讨论(0)
    提交回复
    热议问题