首页 文章

如何替换使用ng-repeat显示的数组中的对象?

提问于
浏览
15

我有一个项目数组,使用ng-repeat显示在表格中 . 当您单击某个项目时,该项目将从服务器中提取,然后应使用更新的项目更新该表格 .

单击表格中的项目时获取更新项目的功能:

$scope.getUpdatedItem = function(item){
    itemService.getItem(item).then(
        function(updatedItem){
            item = updatedItem;
        },
        function(error){
            //Handle error
        }
    );
};

我正在使用以下方式显示项目:

<tr ng-repeat="item in myItems">

问题:表中的项永远不会更新 .

更新ng-repeat中项目的最佳方法是什么?我可以在ng-repeat中使用“追踪$ index”吗?或者我是否必须迭代myItems才能找到我要替换的项目?

Update:

可能的解决方案是使用而不是使用

item = updatedItem,

使用:

var index = $scope.myItems.indexOf(item);
$scope.myItems[index] = updateItem;

但是,我觉得应该采用“更清洁”的方式来做到这一点 .

4 回答

  • 2

    没有更清洁的方式(然后你的更新) . 正如您所注意到的,当您在回调函数中更改 item 时,您更改了本地引用,而不是数组中的原始项 .

    您可以使用 ng-repeat 中的 $index 来改善这一点,而不是自己计算:

    <div ng-click="getUpdatedItem(item, $index)"> </div>
    

    在你的控制器中:

    $scope.getUpdatedItem = function(item, index){
        itemService.getItem(item).then(
        function(updatedItem){
            $scope.myItems[index] = updateItem;
        },
        function(error){
            //Handle error
        }
        );
    };
    

    您也可以使用 angular.copy ,但效率低得多:

    function(updatedItem){
        angular.copy(updateItem, item);
    },
    
  • 0

    如果我理解你的问题

    可能像这样的工作吗?

    <!-- template code -->
    <table>
        ...
        <tr ng-repeat="(index, item) in items">
            <td>{{item.name}}</td>
            <td>
                 {{item.detail}}
                 <button ng-if="!item.detail" ng-click="loadItem(index)">
            </td>
        </tr>
    </table>
    
    // Controller Code
    $scope.items = [...]
    $scope.loadItem = function(index){
        itemService.getItemDetail($scope.items[index]).then(function(itemDetail){
            $scope.items[index].detail = itemDetail;
        });
    };
    
  • 14

    item 可以作为对列表中项目的引用开始,但是当您说:

    item = updatedItem;
    

    您重新安装该绑定 - 您不再引用列表中的项目,而是指您的承诺中返回的已断开连接的项目 . 您需要修改项目,如下所示:

    function(updatedItem){
      item.varA = updatedItem.varA
      item.varB = updatedItem.varB
      ...
    }
    

    或者,如果它太毛茸茸,你可能会认为一个看起来更像是这样的项目数组:

    var items = [ 
      { data: item1 },
      { data: item2 },
      { data: item3 }
    };
    

    此时您的更新功能将如下所示:

    function(updatedItem){
        item.data = updatedItem;
    },
    
  • 1

    我've just spent hours on this issue. I couldn' t使用来自@eladcon的 $index 解决方案,因为我的 ng-repeat 也使用过滤器,如果行/项被过滤,则索引不正确 .

    我以为我能做到这一点:

    $filter('filter')($scope.rows, {id: 1})[0] = newItem;
    

    但这不起作用 .

    我最终迭代数组,直到找到匹配,然后使用迭代中的 $index (而不是来自 ng-repeat )将数组项设置为新项 .

    // i'm looking to replace/update where id = 1
    angular.forEach($scope.rows, function(row, $index) {
      if (row.id === 1) {
        $scope.rows[$index] = newItem;
      }
    })
    

    看这里:https://codepen.io/anon/pen/NpVwoq?editors=0011

相关问题