angular.js - [angular]陣列清空後,視圖沒有馬上更新
PHP中文网
PHP中文网 2017-05-15 16:52:44
0
3
589

最近在開發一個資料清單時遇到問題:
此資料清單有一個搜尋功能,輸入時,會立即根據輸入的關鍵字,從服務端請求搜尋結果。然後視圖馬上渲染結果。具體程式碼如下:

app.controller('ListViewController',function($scope){

    $scope.files=[];

    $scope.vm={
        key:''
    };

    $scope.query=function(){
        var param={
            nameFuzzy:$scope.vm.key
        }
        $http.post(url,param)
            .success(function(resp){
                angular.each(resp,function(item){
                    $scope.files.push(item);
                });
            });
    };

    $scope.$watch('vm.key',function(newVal,oldVal){
        if(newVal!==oldVal){
            //关键词发生变化时,清空列表
            $scope.files.length=0;
            //然后请求数据
            $scope.query();
        }
    });

    $scope.query();
});

現在的問題在於:當清空數組時,視圖上的列表沒有消失,待搜索結果返回後,並渲染成功,前一個列表才消失,也就是說,兩組數據會同時存在幾百毫秒的樣子,前一組資料才消失,呼叫$scope.$apply()並沒有什麼用,會拋出錯誤:degist in progress,說明已經在更新視圖中,但是不知道為什麼會這麼慢。
ps:還有其它資料列表,則沒有這個問題

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(3)
滿天的星座

試試調用scope.$digest();這個有沒有用?

Peter_Zhu

app.controller('ListViewController',function($scope){

$scope.files=[];

$scope.vm={
    key:''
};

$scope.query=function(){
    var param={
        nameFuzzy:$scope.vm.key
    }

    $scope.files=[]; //增加

    $http.post(url,param)
        .success(function(resp){
            angular.each(resp,function(item){
                $scope.files.push(item);
            });
        });
};

});

模版中 關鍵字輸入框 使用ng-change="query()" 就可以了。 不要濫用watch 除非你明白怎麼用

洪涛


`$timeout(function(){
$scope.files = [];
})`

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!