Reload AngularJS Controller

后端 未结 2 735
闹比i
闹比i 2021-02-13 03:28

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

2条回答
  •  伪装坚强ぢ
    2021-02-13 03:49

    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)

    
    

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

    And here is the working example

提交回复
热议问题