AngularJS: HTML 部分 ng-如果 $scope.loggedInUser 更新时不更新

AngularJS: HTML partials ng-if not updating when $scope.loggedInUser is updated

我是 AngularJS 社区的新手,希望有人能帮助我解决以下问题。

我根据一个不完整的教程创建了一个轻型 CMS 系统,并自己填写了一些部分,但是当 $scope 更改时我无法更新 HTML 部分;

HTML 部分 (admin-login.html)

<div ng-if="loggedInUser">
Welcome {{loggedInUser}} |  <a href="admin/pages">My Admin</a> | <a href="admin/logout">Logout</a>
</div>

我的指令(directives.js)

directive('adminLogin', [
  function() {
    return {
      controller: function($scope, $cookies) {
        var user = $cookies.get('loggedInUser', {path: "/"});
        $scope.loggedInUser = user;
      },
      templateUrl: 'partials/directives/admin-login.html'
    };
  }
])

我的控制器(controllers.js)

controller('AdminLoginCtrl', ['$scope', '$location', '$cookies', 'AuthService','$log','flashMessageService',
    function($scope, $location, $cookies, AuthService, $log, flashMessageService) {
      $scope.credentials = {
        username: '',
        password: ''
      };
      $scope.login = function(credentials) {
        AuthService.login(credentials).then(
          function(res, err) {
            $cookies.put('loggedInUser', res.data);
            $location.path('/admin/pages');
          },
          function(err) {
            flashMessageService.setMessage(err.data);

            $log.log(err);
          });
        };
    }
])

范围更新,但我必须刷新页面才能显示或隐藏管理员-login.html。

非常感谢任何帮助,提前致谢。

$scope.loggedInUser 不会在更新 cookie 后更新,您应该注意指令中的 cookie 更改并手动更新 $scope

directive('adminLogin', [
  function() {
    return {
      controller: function($scope, $cookies) {
        $scope.$watch(function () {
          return $cookies.get('loggedInUser', {path: "/"});
        }, function (value) {
          $scope.loggedInUser = value;
        });
      },
      templateUrl: 'partials/directives/admin-login.html'
    };
  }
])