TheCleverIdiot
TheCleverIdiot

Reputation: 410

AngularJs - keeps getting old value of scope even if it is updated

In my application, I'm retrieving some fields from the database and setting the values in local storage when a user logs in.

and then retrieving from local storage to display it to user:

if (localStorage.getItem('a') != undefined) {
            $rootScope.a = localStorage.getItem('a');
    }

So this is working fine. But the problem is when the value gets updated in the database and user logs in after logging out, then even if the local storage has correct value (i.e., recently updated value), the first time it will display the old value of the scope variable which just got updated.

I tried $apply() and also $digest() as suggested in different posts here :

$timeout( function () {
        $scope.$apply( function () {
            $rootScope.a = localStorage.getItem('a');
        });
    });

But it didn't work out. It always displays the old value of scope. It will only display the new value after reloading the page once.

P.S. - The web page in my application won't be reloaded in any module, even when logging in and out.

Upvotes: 0

Views: 678

Answers (1)

Nick
Nick

Reputation: 14283

You can try watching for the scope variable like this:

$rootScope.$watch('a', function (newVal, oldVal){
 if newVal != oldVal
   $rootScope.a = newVal;
}

Something else to try is to change 'a' from string to object as I think that angular watches for values using object reference.

here's some useful reference for $watch

http://www.learn-angular.org/#!/lessons/watch

https://www.bennadel.com/blog/2852-understanding-how-to-use-scope-watch-with-controller-as-in-angularjs.htm

Hope it helps in any way

EDIT

ok I tested it. You don't need watch neither $apply if you refresh the scope when data refreshing.

Here's what I've done:

(function() {
  angular.module('myapp', []).controller('myctrl', [
    '$scope', function($scope) {
      var data, getDataFromLocalStorage;
      console.log("scope is ", $scope);
      getDataFromLocalStorage = function() {
        return JSON.parse(localStorage.getItem('data'));
      };
      data = [
        {
          id: 1,
          text: "test1"
        }, {
          id: 2,
          text: "test2"
        }, {
          id: 3,
          text: "test3"
        }
      ];
      localStorage.setItem('data', JSON.stringify(data));
      $scope.myData = getDataFromLocalStorage();
      return $scope.changeData = function() {
        var dataNew;
        dataNew = [
          {
            id: 4,
            text: 'text4'
          }, {
            id: 5,
            text: 'text5'
          }, {
            id: 6,
            text: 'text6'
          }
        ];
        localStorage.setItem('data', JSON.stringify(dataNew));
        return $scope.myData = getDataFromLocalStorage();
      };
    }
  ]);

}).call(this);

https://codepen.io/NickHG/pen/rzvGGx?editors=1010

Upvotes: 1

Related Questions