如果变量是一个数组,那么我可以将对象插入其中并获取 Controller 内的值,但如果将对象直接分配给该变量,我无法做到这一点
请任何人帮助我实现这一目标。
这是 fiddle 链接
Angular 代码:
//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';
}
关于javascript - 无法将值分配给 Angular 工厂内的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982165/