[英]Not able to assign the value to a variable inside Angular factory?
if the variable is an array , then I am able to push the object inside it and get the value inside controller but in case of assigning the object directly to that variable , I am not able to do it如果变量是一个数组,那么我可以将对象推入其中并在控制器中获取值,但是如果将对象直接分配给该变量,我将无法做到
Please anyone help me to achieve this.请任何人帮助我实现这一目标。
Here is the Fiddle Link这是小提琴链接
Angular Code:角度代码:
//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 Code: 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>
Like said in comment, problem is in references, but here is hack:就像评论中所说的,问题出在参考文献中,但这里是黑客:
//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);
};
}
Your problem is in this code -您的问题出在此代码中-
incrementCount:function(){
//countF.push({aaaa:'jshfdkjsf'});
countF={aaaa:'jshfdkjsf'};
//return countF;
}
here you are not initizalizing aaa property of countF object you are recreating it在这里,您不是在重新创建 countF 对象的 aaa 属性
Initialization - countF = {};
初始化-
countF = {};
Adding a property -添加属性-
right `countF.aaa = "value";`
wrong `countF = { aaa : 'value' }`
Solution -解决方案——
incrementCount:function(){
countF.aaaa = 'jshfdkjsf';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.