更新模型列表后,AngularJS,DOM未更新

时间:2015-01-23 03:18:15

标签: angularjs

我有一个angularjs控制器,里面有一个函数如下所示:

$scope.searchCustomersBy = function(circleuuid) {
    // get all the customers that belong to the circle
    console.log("searchCustomersBy "+circleuuid);
    console.log($scope.customersResults);
    var buddies = [];
    var results = [];
    var promise = $http.get('/api/customer/buddies?circleuuid='+circleuuid);
    promise = promise.then(function(response){
        console.log(response.data);
        buddies = response.data;
        if (buddies.length > 0) {
            for (var i in $scope.customers) {
                if ( buddies.indexOf($scope.customers[i].uuid) >= 0)
                    results.push($scope.customers[i]);
            }
        }


        $scope.customersResults = results;

    }, function(err){
        console.error('failed to fetch the buddy list', err);
    });
};

在html页面中,使用该列表的代码如下:

<div ng-controller="CustomerController">
    ...
    <tbody>
        <tr ng-repeat="customer in customersResults">
        ...
        </tr>
    </tbody>
    ...
</div>

使用angularjs的所有其他部件都可以正常工作。唯一的问题是,在调用searchCustomersBy并更新$scope.customersResults后(我很确定),DOM根本没有更新。

当我把它放在promise

中时,代码似乎根本不起作用

我该如何解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:0)

您的问题是,当您

时,您正在破坏模型与视图之间的关系
$scope.customersResults = results;

你实际上是将$ scope.customersResults指向一个新的内存地址,但旧的数据并没有被垃圾收集,因为它与DOM绑定在一起,所以你对$ scope.customersResults的任何更改都不会被观察到,解决方案这是为了从数组中删除所有内容,而无需重新分配它

$scope.customersResults.splice(0,$scope.customersResults.length)
$scope.customersResults=$scope.customersResults.concat(results);

应该有效