简体   繁体   中英

Data from AngularJS local storage service not rendering unless page refreshed

I am building a small AngularJS project and I have encountered a problem that I want to ask you guys about. I am using angular-local-storage module to store some data coming from my API into the browser's local storage. In one of my controllers I assign this data to a variable in the $scope object and try to render it in the view as follows:

controller:

angular.module('Dashboard')

.controller('DashboardController',
    ['$scope', '$rootScope', 'localStorageService',
        function ($scope, $rootScope, localStorageService) {
            $scope.userData = localStorageService.get('userData');
        }]);

And the view:

<div class="row">
<h4>Welcome to your dashboard <strong>{{userData.personalUserInfo.name}}</strong>!</h4>

When I log into the app (which is when the data is fetched from API and stored in local store by key 'userData'), the view is incomplete, I get only "Welcome to your dashboard !" without the name there. When I go to the dev console and look at the localStorage of my browser, the entry "userData" is there, it is just not rendered. Then when I hit F5 and refresh the page, the name appears.

Do you have any ideas why that is and what can be done to fix that? Cheers!

You have to use $scope.$watch for this, like following:

 $scope.$watch(function() { return localStorageService.get('userData'); }, function(newVal, oldVal) { if (newVal !== oldVal) $scope.userData = newVal; }) 

$scope.$watch , will execute second function each time return value of first function is changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM