首页 > 解决方案 > 带数组的 Angular 和 changling dom 树

问题描述

我有角度的html组件。模板是

              <tr ng-repeat="item in documentList track by $index">
                <td>{{item.TYPE}}</td>
                <td>{{item.DATE_CREATE}}</td>
                <td>
                  <a type="button" class="btn btn-default" ng-click="delDocument(item)">Delete</a>
                </td>
              </tr>

和方法 delDocument(item) 是

  $scope.delDocument = function(item){
    if(confirm('Do you really want to delete document?')) {
      $.ajax('/ajax/del_document.php', {
        'method': 'POST',
        'data': {
          'id': item.ID,
        },
        'success': function(){
          i = 0;
          while(i<$scope.documentList.length) {
            if($scope.documentList[i].ID===item.ID) {
              $scope.documentList.slice(i, 1);
            }
            i++;
          }
        }
      });
    }
  }

所以我希望当用户按下 Delete 按钮时,ajax 会删除后端的元素,然后 documentList 会发生变化,然后 angular 会更改 dom 树。但它没有:documentList 正在改变,但 html 页面仍然是一样的。为什么会发生?我究竟做错了什么?

标签: javascriptarraysangularjsdom

解决方案


执行操作后尝试$scope.$apply()在你的成功函数内部使用。

 $scope.delDocument = function(item){
    if(confirm('Do you really want to delete document?')) {
      $.ajax('/ajax/del_document.php', {
        'method': 'POST',
        'data': {
          'id': item.ID,
        },
        'success': function(){
          i = 0;
          while(i<$scope.documentList.length) {
            if($scope.documentList[i].ID===item.ID) {
              $scope.documentList.slice(i, 1);
            }
            i++;
          }
          $scope.$apply();
          // or blow is a safe way to use $scope.$apply();
          // if($scope.$$phase){
            // $scope.$apply();
          // }
        }
      });
    }
  }

推荐阅读