Angular: update in factory model is not reflected in the controller

I have a factory user preference that contains user preference values. When the page loads, it is blank. After entering the user’s log, it is populated with the 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 paste the factory into 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 } }); 

The return value from the pref factory is not updated in the controller. How can I make it work?

Edit: plunkr http://plnkr.co/edit/SKJC5hUPEm72JqGJyT9y

+4
source share
1 answer

The object returned from pref factory,

 { setPreference: setPreference, currency: pref.currency, name: pref.name, formatTime: formatTime } 

assigns currency and name undefined properties. Since undefined not a reference type, currency and name will not β€œsee” any updates to the pref object.

I suggest instead that the 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 the properties of this object, as indicated in your controller:

 console.log(prefService.prefs.name) 

To not change the link that pref points to, use angular.copy() to change the object that pref refers to:

 function setPreference(values){ //pref = values; <<-- won't work, since pref will now reference another object angular.copy(values,pref); } 

Refresh : to automatically update the view when name changes, I suggest keeping the link to prefs as a property of the scope:

 $scope.prefs = prefService.prefs; 

Then use {{prefs.name}} in the / HTML view:

 <p>Hello {{prefs.name}}!</p> 

Updated plunker

+4
source

Source: https://habr.com/ru/post/1487833/


All Articles