【问题标题】:$scope not updating on change$scope 不更新更改
【发布时间】:2015-07-19 22:42:04
【问题描述】:

我正在使用 Satellizer 进行身份验证,登录后,标题中的登录/注册按钮应该更改为注销,但它们没有。

这是我的头指令:

angular.module('pages.components.navHeader', [
    'common.services.authenticationService'
])

    .directive('navHeader', function () {
                   var directive = {};

                   directive.restrict = "E";
                   directive.templateUrl = "navHeader.tpl.html";
                   directive.controller = ['$scope','$location', 'CONFIG', 'authenticationService', function navHeaderCtrl($scope, $location, CONFIG, authenticationService) {
                       $scope.isAuthenticated = authenticationService.isAuthenticated();

                       $scope.logout = function (){
                           authenticationService.logout();
                       };
                   }];

                   return directive;
               });

这是我的标题模板中有趣的部分:

<li ng-show="!isAuthenticated"><a ng-href="#">Login</a></li>
<li ng-show="!isAuthenticated"><a ng-href="#">Register</a></li>
<li ng-show="isAuthenticated"><a ng-click="logout()" href="#">Logout</a></li>

我有一个工厂作为额外的层,以防卫星器不适合我,这只是一个执行此操作的指令:

   .factory ('authenticationService', ['CONFIG', '$auth', function authenticationService (CONFIG, $auth) {
    var authentication = {};

    authentication.isAuthenticated = function (){
        return $auth.isAuthenticated();
    };
    return authentication;
}])

因此,即使我单击注销,标题也不会更新。我在我的标题中设置 isAuthenticated 的方式有问题吗?

【问题讨论】:

  • 尝试在authenticationService.logout()方法后添加$scope.$apply();
  • 在您的注销功能中添加$scope.isAuthenticated = authenticationService.isAuthenticated();

标签: javascript angularjs angularjs-scope angularjs-ng-show satellizer


【解决方案1】:

把你的控制器代码改成这个

$scope.isAuthenticated = authenticationService.isAuthenticated;

然后在 html 上你可以简单地使用。

ng-show="isAuthenticated()"

注意

ng-show 将在每个 digest 循环中调用 authenticationService.isAuthenticated 方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    相关资源
    最近更新 更多