如何在Angularjs中重新计算变量

时间:2014-07-17 03:39:35

标签: angularjs

HTML

<tr ng-repeat="client in (filteredItems = (clients | filter:searchText | orderBy:sortingOrder:reverse))">
          ....

控制器:

function SomeController($scope,$http) {
    $http.get("http://www.example.com/someapi", function(data) {
        $scope.clients = data; // This code will cause a digest.
        waitUtilDigestEnd()  // I want to block it until the digest ends up so that $scope.filteredItems is up to date. How to write this code?
        handle($scope.filteredItems)
    })
}
function handle(filteredItems) {
   .....
}

我的问题是如何重新计算filteredItems变量以使filteredItems包含最新数据。

2 个答案:

答案 0 :(得分:0)

由于loadAjax()的回调是异步运行的,它将在Angular上下文之外执行,这意味着Angular不会知道发生了什么变化。

为了让Angular了解更改,您应该将代码包装在$scope.$apply()中:

loadAjax('...', function (data) {
    $scope.$apply(function () {
        $scope.data = data;
        ...
    });
});

<强>更新

如果您想在其余任务完成后致电handleFilteredData(),可以将其打包在$evalAsync()中:

loadAjax('...', function (data) {
    $scope.data = data;
    ...
    $scope.$evalAsync(function () {
        handleFilteredData($scope.filteredItems);
    });
});

<子> 这种方法似乎没有多大意义,因为只要搜索查询或排序顺序发生变化,filteredItems就会发生变化,而对于这些情况,handleFilteredData()不会被调用。那么,为什么要处理filteredItems而不只是处理data(未经过滤)?

答案 1 :(得分:0)

我在AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

找到解决方案
$timeout(function() {
    // anything you want can go here and will safely be run on the next digest.
    handle($scope.filteredItems)
})