如果变量是数组,那么我可以将对象推入其中并在控制器内获取值,但是如果直接将对象分配给该变量,则无法执行该操作
请任何人帮助我实现这一目标。
这是小提琴链接
角度代码:
//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>
最佳答案
您的问题出在此代码中-
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';
}