![](/img/trans.png)
[英]Not able to assign data of a local variable inside Promise to outside variable
[英]Not able to assign the value to a variable inside Angular factory?
如果变量是一个数组,那么我可以将对象推入其中并在控制器中获取值,但是如果将对象直接分配给该变量,我将无法做到
请任何人帮助我实现这一目标。
这是小提琴链接
角度代码:
//angular.js example for factory vs service
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
var countF={};//= [{abc:'aaa'}];
return {
getCount : function () {
return countF;
},
incrementCount:function(){
//countF.push({aaaa:'jshfdkjsf'});
countF={aaaa:'jshfdkjsf'};
//return countF;
}
}
});
function FactoryCtrl($scope,testFactory)
{
$scope.countFactory = testFactory.getCount();
$scope.clickF = function () {
testFactory.incrementCount();
// console.log($scope.countFactory);
};
}
HTML代码:
<div ng-controller="FactoryCtrl">
<!-- this is never updated after count is changed! -->
<p> This is my countFactory variable : {{countFactory}}</p>
<p> This is my updated after click variable : {{countF}}</p>
<button ng-click="clickF()" >Factory ++ </button>
</div>
就像评论中所说的,问题出在参考文献中,但这里是黑客:
//angular.js example for factory vs service
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
var countF={};//= [{abc:'aaa'}];
var getCountF = function(){
return countF;
};
var setCountF = function(arg){
countF = arg;
};
return {
getCount : getCountF,
setCount : setCountF,
incrementCount:function(){
//countF.push({aaaa:'jshfdkjsf'});
countF={aaaa:'jshfdkjsf'};
//return countF;
}
}
});
function FactoryCtrl($scope,testFactory)
{
$scope.countFactory = testFactory.getCount();
$scope.clickF = function () {
testFactory.incrementCount();
// console.log($scope.countFactory);
};
}
您的问题出在此代码中-
incrementCount:function(){
//countF.push({aaaa:'jshfdkjsf'});
countF={aaaa:'jshfdkjsf'};
//return countF;
}
在这里,您不是在重新创建 countF 对象的 aaa 属性
初始化- countF = {};
添加属性-
right `countF.aaa = "value";`
wrong `countF = { aaa : 'value' }`
解决方案——
incrementCount:function(){
countF.aaaa = 'jshfdkjsf';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.