如果变量是一个数组,那么我能够将对象推入其中并获取控制器内的值,但是如果将对象直接分配给该变量,我无法做到这一点
请有人帮助我实现这一目标。
这是小提琴链接
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代码:
<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>
答案 0 :(得分:1)
如评论中所述,问题在于引用,但这里是黑客:
//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);
};
}
答案 1 :(得分:1)
您的问题在此代码中 -
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';
}