0

全部:

我对角度摘要很陌生,现在,当我使用 Promise 时,在其 then 函数中,我必须使用 $scope.$digest() 使范围变量更改在其他地方生效,例如:

这里我使用 Promise 来模拟 $http 请求,我的困惑在于 $scope.getdata,为什么我需要调用 $scope.$digest(),我认为 $scope.disable 应该由 angular 自动监视。

var app = angular.module("vp", []);
app
    .service("srh", function($http){
        var busy = false;
        this.get = function(url){
            if(!busy){
                busy = true;
                var p = new Promise(function(res, rej){
                            $timeout(function(){
                                res("data is fetched");
                            }, 3000);
                        })
                        .then(function(data){
                            busy = false;
                            return data;
                        }, function(data){
                            busy = false;
                            return data;
                        });
                return p;
            }else {
                return null;
            }
        }
    })// end of service
    .controller("main", function($scope, srh){
        $scope.disable = false;
        $scope.getdata = function(){
            var dp = srh.get("");
            if( dp ) {
                $scope.disable = true;
                dp.then(function(data){
                    console.log(data);
                    $scope.disable = false;
                    $scope.$digest()
                })
            }
        }
    })
4

1 回答 1

2

使用将在内部处理所有摘要要求的$q角度承诺。

每当您使用修改范围的角度核心之外的事件时,您需要告诉角度以便它可以更新视图

于 2016-01-25T23:39:43.070 回答