Search code examples
angularjsrootscope

$rootScope changed doesn't reflect on template


I'm a newbie in angularjs. I'm trying to build a simple app which contain login page and dashbboard page.

Now, I got a problem with updating html template when rootScope changed.

Here is my component template :

<!-- show dashboard page app >
<div layout="column">
  <div ng-show="$rootScope.isAuthenticated">
    <pm-header></pm-header>
    <div layout="row">
      <pm-sidebar></pm-sidebar>
      <div layout="column" class="sitecontent" layout-padding>
        <md-content ui-view></md-content>
      </div>
    </div>
  </div>

  <!-- show login page app >
  <div ng-hide="$rootScope.isAuthenticated">
    <pm-homeheader></pm-homeheader>
    <div layout="row">
      <md-content ui-view flex></md-content>
    </div>
  </div>

</div>

Login blockcodes :

'use strict'

export default ['$rootScope', '$state', '$http', '$window', function($rootScope, $state, $http, $window) {
  this.user = {};

  this.login = () => {
    $http.post('./api/auth/login', this.user)
      .success(function(data, status, headers, config) {
        $window.sessionStorage.token = data.token;

        $rootScope.user = data.user;
        $rootScope.isAuthenticated = true;

        $state.go('home');
      })
      .error(function(data, status, headers, config) {
        delete $window.sessionStorage.token;
      })
  };
}]

My problem is when I logged and go back to home state, the ui-router updated the template to ui-view, but the ng-show="$rootScope.isAuthenticated" didn't reflect the changes on html, it show the block codes of home page instead of dashboard page.

Can anyone help me for this case, many thanks.


Solution

  • Use:

    ng-show="$root.isAuthenticated"
    

    You can't access $rootScope in the template, when you access it in a controller you inject it in. $root works because when angular creates a rootScope it sets a reference to $root to itself so its just like accessing any other property on the scope.

    Refer to AngularJS rootScope code Line 135: https://github.com/angular/angular.js/blob/v1.3.6/src/ng/rootScope.js#L135