pham cuong
pham cuong

Reputation: 871

$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.

Upvotes: 3

Views: 3354

Answers (2)

lahsrah
lahsrah

Reputation: 9173

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

Upvotes: 8

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

You should not use either $scope OR $rootScope while using variable for binding on HTML, so as soon as variable update in $rootScope, isAuthenticated will be taken from $rootScope while evaluating value of ng-show.

ng-show="isAuthenticated"

Though directly using $rootScope, wouldn't consider as a good practice. I'd suggest you to create a service/factory with a name userService that will have shareable user information among-st angular components.

Upvotes: 1

Related Questions