service - How to properly share and update data between Controllers in AngularJS? -


so trying code angularjs best practice way without using $scope or $rootscope, named controllers.

http://codepen.io/anon/pen/lpxowx

here's angular part:

.controller('democontroller', function(fac){   var vm = this;   vm.theme = fac.theme;   vm.changetheme = function(theme) {     fac.changetheme(theme);     vm.theme = fac.theme;   };  })  .controller('secondcontroller', function(fac){   var vm = this;   vm.changetheme = function(theme) {     fac.changetheme(theme);   };  })   .factory('fac', function() {   var fac = {   theme: '',   changetheme: function(theme) {     fac.theme = theme === 'indigo' ? 'lime' : 'indigo';    } } return fac; }); 

i have forked codepen illustrate problem. democontroller works intended , updates view. doesn't "work" when using same factory in secondcontroller. assume works, doesn't update in democontroller.

the way understood angular data binding is, need use factory share data between controllers bind them , update accordingly on change.

i sure, it's stupid mistake i'm doing here. doing wrong?

update:

thanks answers! i've encountered new (related?) problem though:

http://plnkr.co/edit/cra2ftkpbisj9tlzu5bd?p=preview

can tell me how bind user between loginctrl , toolbarctrl ng-show , ng-hide can update upon login , logout? when login toolbar doesn't update accordingly. have refresh whole page instead make login visible. when logout works because explicitly set vm.user= {}; in toobarctrl.

here working version of codepen

i used subvar bind view. binding primitive var factory controller lead king of trouble.

the factory :

.factory('fac', function() {     var fac = {       theme: {value:'indigo'},       changetheme: function(theme) {         console.log(theme);         fac.theme.value = theme === 'indigo' ? 'lime' : 'indigo';        }     } 

both controllers :

.controller('secondcontroller', function(fac){       var vm = this;       vm.theme = fac.theme;       vm.changetheme = fac.changetheme;   }) 

and used in view :

<md-button href="#" class="md-primary md-raised" ng-click=vm.changetheme(vm.theme.value)>   change theme </md-button> 

hope helped,

edit : here answer explain why don't work primite var


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -