我有一个保存用户偏好值的用户偏好工厂。当页面加载时它是空的。用户登录后,它会填满用户配置文件。 伪代码
app.factory('pref', function($rootScope){
var pref = {}, age, name;
$rootScope.$on('logged.in', function(){
pref.name = 'sam';
pref.age = 30;
pref.currency = '$';
age = getAge(); name = getName();
})
function getName(){
//format name
return name;
}
function getAge(){
return age;
}
return {
currency: pref.currency,
age: age,
name: name
}
})
然后我将工厂注入(inject)到我的 Controller 中:
app.controller('MainCtrl', function($scope, pref) {
$scope.name = pref.name; //Return undefined
var currency = pref.currency;
$scope.price = function(amount){
return amount + currency; //don't show $ sign
}
});
pref 工厂的返回值未在 Controller 中更新。我如何让它发挥作用?
最佳答案
从pref
工厂返回的对象,
{ setPreference: setPreference,
currency: pref.currency,
name: pref.name,
formatTime: formatTime }
将 currency
和 name
分配给未定义的属性。由于 undefined
不是引用类型,currency
和 name
将不会“看到”对象 pref
的任何更新。
我建议将引用 pref
对象的属性作为工厂返回对象的一部分:
{ setPreference: setPreference,
prefs: pref,
formatTime: formatTime }
现在,我们对 pref
所做的任何更新都将反射(reflect)在 prefs
中。在您的 Controller 中引用该对象的属性,如下所示:
console.log(prefService.prefs.name)
为了不改变pref
指向的引用,使用angular.copy()
修改pref
引用的对象:
function setPreference(values){
//pref = values; <<-- won't work, since pref will now reference another object
angular.copy(values,pref);
}
更新:要在 name
更改时自动更新 View ,我建议将对 prefs
的引用保存为范围属性:
$scope.prefs = prefService.prefs;
然后在 View /HTML 中使用{{prefs.name}}
:
<p>Hello {{prefs.name}}!</p>
已更新 plunker
关于javascript - Angular : update in factory model does not reflect in controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17270434/