【问题标题】:AngularJS: HTML partials ng-if not updating when $scope.loggedInUser is updatedAngularJS:HTML部分ng-如果更新$ scope.loggedInUser时不更新
【发布时间】:2017-02-10 12:38:41
【问题描述】:

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

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

非常感谢您的帮助,在此先感谢您。

【问题讨论】:

    标签: angularjs angularjs-directive angular-ng-if


    【解决方案1】:

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

    【讨论】:

    • 非常感谢,当您知道如何操作时如此简单 - 再次感谢您
    • 是的,当你开始学习 Angular 时,它是相当复杂的,继续学习,你会发现它有多有趣!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多