【问题标题】:Refreshing ng-repeat without $scope, without new request to sever在没有 $scope 的情况下刷新 ng-repeat,没有新的服务器请求
【发布时间】:2016-10-08 05:21:18
【问题描述】:

我有一张包含以下内容的表格:

 <tbody>
     <tr ng-repeat="result in ctrl.result track by $index">
       <td ng-bind="$index+1"></td>
       <td ng-bind="::result.title"></td>
       <td> <button type="button" class="btn" ng-click='ctrl.deleteItem(result)'>Delete</button></td>
     </tr>
 </tbody>  

在我的控制器中我有:

 vm.deleteItem = function (result) {
        myService.deleteItem(result.id)
           .then(function (response) {
                vm.result.splice(result, 1);
            });
    };

如您所见,如果成功删除项目,vm.result 已更改。 现在,该项目已在 db 中删除,因此我们有响应,然后该项目也已从 vm.result 中删除。但该列表尚未在浏览器中更新。
如您所见,我使用 controller as 方法而不是 $scope

【问题讨论】:

  • 嗨,你必须在你的 html 中使用 vm.result 因为在你的控制器中你有 vm.result 如果它只有 $scope.result 它将被认为是 html 中的结果所以改变 vm.result html
  • 您应该尝试从ng-bind 中删除::。因为它不仅仅是只读数据!
  • @gayathri,我已将 myController 设置为 ctrl。所以我用vm。在控制器和 ctrl.在 html 中。
  • @DhavalMarthak,++投票给你的评论!

标签: angularjs angularjs-ng-repeat angularjs-controlleras


【解决方案1】:

尝试以这种方式删除项目:

vm.result.splice(vm.result.indexOf(result), 1);

第一个Splice参数应该是元素的索引而不是元素本身。

【讨论】:

  • 我接受了答案。但是@Dhaval Marthak 的评论也对我有帮助。如果我不删除 ::,它将无法正常工作。
  • @Elnaz 很高兴它有帮助:)
【解决方案2】:
     var index = vm.result.findIndex(function(item) {
                if (item.id == test.id) {
                    return true;
                }
            });

            if (index !== -1) {
                // Removing the test from list;
                vm.result.splice(index, 1);
}

根据数组 test.id 中的 id 检查是否是要删除的元素的 id

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 1970-01-01
    • 2015-11-28
    • 2020-01-14
    • 2017-04-27
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    相关资源
    最近更新 更多