Angular: Update In Factory Model Does Not Reflect In Controller
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(
Solution 1:
The object returned from the pref
factory,
{ setPreference:setPreference,
currency:pref.currency,
name:pref.name,
formatTime:formatTime }
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
.
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 }
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)
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);
}
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;
Then use {{prefs.name}}
in the view/HTML:
<p>Hello {{prefs.name}}!</p>
Updated plunker
Post a Comment for "Angular: Update In Factory Model Does Not Reflect In Controller"