<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