问题描述
我有一个保存用户首选项值的用户首选项工厂.页面加载时为空.用户登录后,将用用户个人资料填充.伪代码
I have a user preference factory that holds user preference values. When the page loads it is empty. After user logs in it is filled up with user profile. pseudo code
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
}
})
然后我将工厂注入控制器中:
Then I inject the factory in my 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
}
});
首选工厂中的返回值未在控制器中更新.我该如何运作?
Return value from pref factory not updating in controller. How do I make it work?
plunkr http://plnkr.co/edit/SKJC5hUPEm72JqGJyT9y
推荐答案
从pref
工厂返回的对象,
{ setPreference: setPreference,
currency: pref.currency,
name: pref.name,
formatTime: formatTime }
将currency
和name
分配给未定义的属性.由于undefined
不是引用类型,因此currency
和name
不会看到"对象pref
的任何更新.
assigns currency
and name
to undefined properties. Since undefined
is not a reference type, currency
and name
will not "see" any updates to object pref
.
我建议将引用pref
对象的属性作为工厂返回的对象的一部分:
I suggest instead that a property that references the pref
object be part of the object returned by the factory:
{ setPreference: setPreference,
prefs: pref,
formatTime: formatTime }
现在,我们对pref
所做的任何更新都将反映在prefs
中.在您的控制器中,请参考该对象的属性,如下所示:
Now, any updates we make to pref
will be reflected in prefs
. Refer to properties of that object as follows in your controller:
console.log(prefService.prefs.name)
为了不更改pref
指向的引用,请使用angular.copy()
修改pref
引用的对象:
In order to not change the reference that pref
points to, use angular.copy()
to modify the object that pref
references:
function setPreference(values){
//pref = values; <<-- won't work, since pref will now reference another object
angular.copy(values,pref);
}
更新:要使视图在name
更改时自动更新,建议将对prefs
的引用保存为范围属性:
Update: to have the view automatically update when the name
changes, I suggest saving a reference to prefs
as a scope property:
$scope.prefs = prefService.prefs;
然后在视图/HTML中使用{{prefs.name}}
:
Then use {{prefs.name}}
in the view/HTML:
<p>Hello {{prefs.name}}!</p>
更新后的
Updated
这篇关于角度:工厂模型中的更新未反映在控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!