从角度$scope承诺中删除一行

Remove a row from an angular $scope promise

本文关键字:一行 删除 scope 承诺      更新时间:2023-09-26

Angular 足够聪明,可以直接绑定承诺。 我有一个ng-grid实例,它绑定到从服务返回的承诺。 稍后我想删除该网格中的一条记录,但不确定如何做到这一点,因为我没有可以直接操作的数组。

例如,以下内容将抛出错误"TypeError:对象#没有方法'splice'",因为"gridData"实际上不是一个数组。

//Bind promise directly to scope (get returns a promise not an array)
$scope.gridData = myService.get();
//Later I remove a row based on user a user clicking a button on the grid row.
var function = removeRow(rowIdx)
    { 
       $scope.gridData.splice(rowIdx, 1);
    };

最终,如何将范围值设置为承诺,同时仍直接操作数据?

承诺解析

后,无法更改其值。

您可以做的是将实际值设置为 scope 属性并修改此值。事实上,你应该尽快摆脱承诺。

//Bind promise directly to scope (get returns a promise not an array)
myService.get().then(function (resolved) {
    $scope.gridData = resolved;
});
//Later I remove a row based on user a user clicking a button on the grid row.
function removeRow(rowIdx) { 
   $scope.gridData.splice(rowIdx, 1);
};
底层

数据数组在$scope.gridOptions.ngGrid.data处公开(假设您的ngGrid绑定到gridOptions ( - 你可以直接操作它,尽管我没有尝试过这个

有多种方法可以做到这一点。其中之一是编写过滤器来对数组进行切片:

.filter("slice", function () {
    return function (array, begin, end) {
        if (!angular.isArray(array)) return;
        return array.slice(begin, end);
    };
});

并在 ng-repeat 中的集合中使用它:

<li ng-repeat="item in (data|slice:1)">{{item}}</li>

工作示例。

此外,由于您的数据是从 promise 返回的,因此没有什么能阻止简单地添加到控制器:

$scope.gridData = myService.get().then(function (data) {
    return data.slice(1)
});

工作示例。