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:
<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
Initialization - countF = {};
Adding a property -
right `countF.aaa = "value";`
wrong `countF = { aaa : 'value' }`
Solution -
incrementCount:function(){
countF.aaaa = 'jshfdkjsf';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.