【问题标题】:$rootScope changed doesn't reflect on template$rootScope 更改不会反映在模板上
【发布时间】:2016-04-13 15:15:19
【问题描述】:

我是 angularjs 的新手。我正在尝试构建一个包含登录页面和仪表板页面的简单应用程序。

现在,当 rootScope 更改时,我在更新 html 模板时遇到了问题。

这是我的组件模板:

<!-- 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>

登录块代码:

'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;
      })
  };
}]

我的问题是当我登录并回到主页状态时,ui-router 将模板更新为 ui-view,但 ng-show="$rootScope.isAuthenticated" 没有反映 html 上的更改,它显示了主页的块代码而不是仪表板页面。

谁能帮我解决这个问题,非常感谢。

【问题讨论】:

  • 确保您的浏览器支持 sessionStorage。

标签: angularjs rootscope


【解决方案1】:

用途:

ng-show="$root.isAuthenticated"

您无法在模板中访问 $rootScope,当您在控制器中访问它时,您将其注入。$root 有效,因为当 Angular 创建一个 rootScope 时,它​​会将 $root 的引用设置为自身,因此它就像访问任何范围内的其他属性。

参考AngularJS rootScope代码第135行:https://github.com/angular/angular.js/blob/v1.3.6/src/ng/rootScope.js#L135

【讨论】:

  • 谢谢@lahsrah。有效 !。但是你能解释一下为什么我不能直接使用 $rootScope 吗?
  • @pcuong 我试图在上面的答案中添加解释^。
【解决方案2】:

你不应该使用$scope OR $rootScope 同时使用变量来绑定HTML,所以一旦$rootScope 中的变量更新,isAuthenticated 将取自@987654325 @ 同时评估 ng-show 的值。

ng-show="isAuthenticated"

虽然直接使用$rootScope,但不认为是一种好习惯。我建议您创建一个名称为 userService 的服务/工厂,该服务/工厂将在 Angular 组件之间具有可共享的用户信息。

【讨论】:

  • 嗨@Pankaj Parkar:我试过了,但没有用:(
  • @pcuong 这应该可以工作.. 你能创建一个 plunkr 吗?
  • 它与 ng-show="$root.isAuthenticated" 作为 lahsrah 评论一起使用。
猜你喜欢
  • 2020-04-22
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
相关资源
最近更新 更多