重新加载 AngularJS 控制器 [英] Reload AngularJS Controller

查看:29
本文介绍了重新加载 AngularJS 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angularjs 的新手.

我的问题是我有一个用于处理登录和注销的用户控制器.我还有另一个控制器可以为我的网站加载标题菜单.

如果用户登录到站点,我的 isAuthenticated 变量将设置为 true.如果变量设置为 true,标题应该更改但是,所以我认为必须重新加载控制器以更改标题视图.

这里是我的 HeaderController 的代码:

myapp.controller('HeaderController', ['$scope', '$location', '$window', 'AuthenticationService',函数 HeaderController($scope, $location, $window, AuthenticationService) {$scope.isAuthenticated = AuthenticationService.isAuthenticated;如果(AuthenticationService.isAuthenticated){$scope.user.vorname = $window.sessionStorage.user.vorname;}}]);

这是我的 HeaderDirective 的代码:

myapp.directive('appHeader', function() {返回 {限制:'E',链接:功能(范围,元素,属性){if (attrs.isauthenticated == 'false') {scope.headerUrl = 'views/header/index.html';} 别的 {scope.headerUrl = 'views/header/isAuthenticated.html';}},模板:'<div ng-include="headerUrl"></div>'}});

我的 index.html:

<app-header isauthenticated="{{isAuthenticated}}"></app-header>

如果用户登录页面,我如何重新加载控制器?

PS:请原谅我糟糕的发音.

解决方案

无需重新加载控制器.Angular 足够聪明,可以在 $scope.isAuthenticated 状态更改时更改模板.

我在您的代码中看到的一个问题是,一旦定义了 $scope.isAuthenticated,它就不再更改.我想您在用户登录时设置 AuthenticationService.isAuthenticated = true 但该更改不会传播到 $scope.isAuthenticated 属性,因为在 JavaScript 中复制了标量值按值而不是按引用.

有很多方法,例如将 AuthenticationService.isAuthenticated 属性从布尔值更改为函数:

angular.module('auth', []).factory('AuthenticationService', function () {//私有状态var isAuthenticated = false;//获取器和设置器var auth = 函数(状态){if (typeof state !== 'undefined') { isAuthenticated = state;}return isAuthenticated;};//暴露 getter-setter返回 { isAuthenticated: auth };});

然后将该函数分配给 $scope:

$scope.isAuthenticated = AuthenticationService.isAuthenticated;

然后使用模板中的函数(不要忘记括号)

<app-header isauthenticated="{{ isAuthenticated() }}"></app-header>

在写一个 plunk 向您展示一个工作示例时,我意识到指令的链接函数不会被多次调用,因此在 这个stackoverflow 线程 我只是修改了指令以观察isauthenticated 属性的变化:

angular.module('指令', []).directive('appHeader', function() {var bool = {'真':真,'假':假};返回 {限制:'E',链接:函数(范围、元素、属性){attrs.$observe('isauthenticated', function (newValue, oldValue) {if (bool[newValue]) { scope.headerUrl = 'authenticated.html';}else { scope.headerUrl = 'not-authenticated.html';}});},模板:'<div ng-include="headerUrl"></div>'}});

还有这里是工作示例

I'm a newbie to angularjs.

My problem is that I have a User Controller for handling Login and Logout. I have also another controller to load a header menu for my site.

If the user logs in to the site my isAuthenticated variable is set to true. If the variable is set to true the header should be change but, so I think the controller must be reloaded to change the header view.

Here the code of my HeaderController:

myapp.controller('HeaderController', ['$scope', '$location', '$window', 'AuthenticationService',  
    function HeaderController($scope, $location, $window, AuthenticationService) {
        $scope.isAuthenticated = AuthenticationService.isAuthenticated;

        if (AuthenticationService.isAuthenticated) {
            $scope.user.vorname = $window.sessionStorage.user.vorname;
        }
    }
]);

Here's the code of my HeaderDirective:

myapp.directive('appHeader', function() {
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      if (attrs.isauthenticated == 'false') {
        scope.headerUrl = 'views/header/index.html';
      } else {
        scope.headerUrl = 'views/header/isAuthenticated.html';
      }
    },
    template: '<div ng-include="headerUrl"></div>'
  }
});

My index.html:

<div ng-controller="HeaderController">
  <app-header isauthenticated="{{isAuthenticated}}"></app-header>
</div>

How can I reload the controller if the user logs in to the page?

PS: Please excuse my poor pronunciation.

解决方案

There's no need to reload your controller. Angular is smart enough to change the template when the $scope.isAuthenticated state changes.

One problem I see in your code is that once the $scope.isAuthenticated is defined it does not change anymore. I suppose you are setting AuthenticationService.isAuthenticated = true when user logs in but that change aren't being propagated to the $scope.isAuthenticated property because in JavaScript scalar values are copied by value instead of by reference.

There are many approaches, such as changing the AuthenticationService.isAuthenticated property from a boolean to a function:

angular.module('auth', [])
.factory('AuthenticationService', function () {
    // private state
    var isAuthenticated = false;

    // getter and setter
    var auth = function (state) {
        if (typeof state !== 'undefined') { isAuthenticated = state; }
        return isAuthenticated;
    };

    // expose getter-setter
    return { isAuthenticated: auth };
});

Then assign that function to the $scope:

$scope.isAuthenticated = AuthenticationService.isAuthenticated;

Then use the function in your template (don't forget the parens)

<app-header isauthenticated="{{ isAuthenticated() }}"></app-header>

Edit:

While writing a plunk to show you a working example I have realized that the link function of the directive is not called more than once, so as exposed in this stackoverflow thread I just modified the directive to observe changes in the isauthenticated attribute:

angular.module('directives', [])
.directive('appHeader', function() {
  var bool = {
    'true': true,
    'false': false
  };

  return {
    restrict: 'E',
    link: function (scope, element, attrs) {
      attrs.$observe('isauthenticated', function (newValue, oldValue) {
        if (bool[newValue]) { scope.headerUrl = 'authenticated.html'; }
        else { scope.headerUrl = 'not-authenticated.html'; }
      });
    },
    template: '<div ng-include="headerUrl"></div>'
  }
});

And here is the working example

这篇关于重新加载 AngularJS 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆