首页 > Angularjs中的factory在promise之后,如何更新在controller中的数据?

Angularjs中的factory在promise之后,如何更新在controller中的数据?

app.factory('mainClass',function($http,mainFac){
        var mainClass=function(){
            this.uid;
            this.sid;
            this.getUid();
        }
        mainClass.prototype.getUid=function(){
            var promise = mainFac.query('OPT','PARM1','PARM2');
            promise.then(function(data){
                console.info("mainClass is :",data);
                this.sid=data.sid;
                console.info("this.sid :",this.sid);
            });
        };
        return mainClass;
    });
    
app.controller('perCenterCtrl', function($scope, $http, $state, ngDialog,
            qfact, myfactory,mainFac,mainClass) {
        var mainObj=new mainClass();
        console.info("mainObj is :",mainObj);
        $scope.sid=mainObj.sid;
});

代码目的:
controller顺序执行,遇到名为mainClass的factory初始化,mainClass异步初始化,从后台拿到数据并更新自己的this.sid,此时在controller中也更新$scope.sid;
遇到困难:
我的理解是:$scope.sid=mainObj.sid;已经绑定了,在mainClass执行过程,异步地从后台拿到数据并更新自己的this.sid后,$scope.sid应相应更新自己的值,可是并没有更新;


app.factory('mainClass',function(mainFac){
        function getUid(){
            mainFac.query('OPT','PARM1','PARM2').then(function(response){
                return response;
            },function(error){
                return error;
            });
        }
        
        return {getUid};
    });
    
app.controller('perCenterCtrl', function($scope, $http, $state, ngDialog,
            qfact, myfactory,mainFac,mainClass) {
        mainClass.getUid().then(function(data){
            console.info("mainObj is :",data);
            $scope.sid=data.sid;
        });
});

没太看懂,你这么写写试试。建议你看看这个:http://each.sinaapp.com/angular/tutorial/ng-factory.html

【热门文章】
【热门文章】