How to access updated value in different page controllers?

664 views Asked by At

I have a problem with getting updated value between in different page controller, Here is the situation.

page1.html

<body ng-app="app">
<div  ng-controller="ctrl1">{{ version }}</div>
</body>

page2.html

<body ng-app="app">
<div  ng-controller="ctrl2">{{ version }}</div>
</body>

app.js

 var app = angular.module("app", []);

 app.run(function($rootScope) {
   $rootScope.Data = [];
   $rootScope.Data.Version = '1.0.0.1';
 });

  app.controller('ctrl1', function($scope, $rootScope){
   $scope.version = $rootScope.Data.Version;
   $rootScope.Data.Version = '1.0.0.2';
  });

 app.controller('ctrl2', function($scope, $rootScope){      
   $scope.version = $rootScope.Data.Version;
 });

Result

version: 1.0.0.1 // page1.html 
version: 1.0.0.1 // page2.html 

Expected Result

version: 1.0.0.1 // page1.html 
version: 1.0.0.2 // page2.html 

How to achieve this kind situation?

I tried using $broadcast from this tutorial for seprate page controllers: fiddle

3

There are 3 answers

3
Jan Peša On BEST ANSWER

You can't just reload pages without losing all your data, you know that? Your $rootScope dies, everything dies... :) Your example is completely wrong. Either use SPA routing which doesn't force browser reload or use some type of local storage for keeping the data safe.

Also I have noticed that you are binding to primitives $scope.version = $rootScope.Data.Version; - don't do that, use $scope.data = $rootScope.Data; and then {{data.Version}}. Anyway you should not be using $rootScope at all.

2
ipln On

Pass the values between controller use broadcast and on method. please refer the link http://www.dotnet-tricks.com/Tutorial/angularjs/HM0L291214-Understanding-$emit,-$broadcast-and-$on-in-AngularJS.html

0
Dmitri Algazin On

You know what I found after using Angular for 2 years now, that using direct variables like $scope.version is not the best for Angular, because they add different watches and in your case you are rewriting instance of 'version'.

Anyway, try to write like that everything what is getting synchronized between different controllers, services, directives, and so on.

    var state = {
        version: $rootScope.Data.Version,
        anyOtherVariable: value
    };
    $scope.state = state;