0

I am working on an application were index page and inside that I am showing multiple views, In index nav bar I have to show notification count and User name which comes from 2 different controllers,

I am able to display the notification count and User name successfully, but the issue is the values are not changing dynamically. We need to refresh the page for the new values.

What can I do in this situation can any one please guide me.

User123
  • 289
  • 3
  • 17
  • Please create a jsfiddle. You should consider moving shared variables into a service that you would inject into your controllers, or resolve during routing. – cl3m Feb 10 '16 at 12:44
  • see http://stackoverflow.com/questions/11938380/global-variables-in-angularjs – wonderbell Feb 10 '16 at 12:59

2 Answers2

0

You can achieve it by:

  1. Maintain those values in rootScope so that you will have the two way binding.

  2. Making use of emit to notify the parent controller about value changes. This will work only if those two controllers are present in child elements.

In child controllers fire event on value update:

$scope.$emit('valueChanged', {value: val});

In parent controller receive event value:

$scope.$on('valueChanged', function(event, args) { console.log(args.value); });

MrNobody007
  • 1,827
  • 11
  • 32
0

I'm guessing you're watching the value directly and not by some object wrapper. In this case javascript isn't actually updating the variable, but assigning a complete new one. Anything out of the function scope that updates the variable will never receive the new value.

The solution is simple; wrap the value in an object and share/inject that object.

angular.module('myApp')
       .value('myPageState', { 
  notificationCount: 0 
});

angular.module('myApp')
       .controller('myController', function($scope, myPageState) {
  $scope.myPageState = myPageState;
});

<div class="my-notification-thingy"> {{ myPageState.notificationCount }} </div>
null
  • 7,906
  • 3
  • 36
  • 37