Angularjs中的factory在promise之後,如何更新在controller中的資料?

WBOY
發布: 2016-08-04 09:21:07
原創
789 人瀏覽過

<code>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;
});
</code>
登入後複製
登入後複製

程式碼目的:
controller順序執行,遇到名為mainClass的factory初始化,mainClass非同步初始化,從後台拿到資料並更新自己的this.sid,此時在controller中也更新$scope.sid;
遇到困難:
我的理解是:$scope.sid=mainObj.sid;已經綁定了,在mainClass執行過程,異步地從後台拿到資料並更新自己的this.sid後,$scope.sid應相應更新自己的值,可是並沒有更新;

回覆內容:

<code>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;
});
</code>
登入後複製
登入後複製

程式碼目的:
controller順序執行,遇到名為mainClass的factory初始化,mainClass非同步初始化,從後台拿到資料並更新自己的this.sid,此時在controller中也更新$scope.sid;
遇到困難:
我的理解是:$scope.sid=mainObj.sid;已經綁定了,在mainClass執行過程,異步地從後台拿到資料並更新自己的this.sid後,$scope.sid應相應更新自己的值,可是並沒有更新;

<code>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;
        });
});
</code>
登入後複製

沒太看懂,你這麼寫寫試試。建議你去看看這個:http://each.sinaapp.com/angular/tutorial/ng-factory.html

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!