AngularJS:观察服务变量和显示/隐藏元素的变化

时间:2014-03-19 07:15:25

标签: angularjs angularjs-directive angularjs-service

我将服务定义为

app.service('Auth', ['$http',function ($http) { this.isLoggedIn = false; this.user = null; }]

并且控制器将其用作

app.controller('AuthenticationController', ['$rootScope','$scope', '$http', '$location', 'Auth',function($rootScope,$scope, $http, $location, Auth){
    $scope.login = function(){
        Auth.isLoggedIn = true;
        Auth.user = {
            name: "Shahzad Fateh Ali",
            id: 1
        };

        $location.path('/users');
    }}]);

我的DOM将其用作

<header ng-show="Auth.isLoggedIn">...</header>

 <mainmenu ng-show="Auth.isLoggedIn"></mainmenu>

这里的主菜单是一个指令。

现在,我想观察Auth.isLoggedIn并根据其值更新DOM。

此致

Shahzad Fateh Ali

2 个答案:

答案 0 :(得分:0)

您可以在函数上创建$watch,它不必是作用域上属性的字符串名称。所以像这样:

$scope.$watch(function() { return Auth.isLoggedIn; }, function(value, oldValue) {
  // Do something when it changes
});

但我鼓励你在这里使用活动。因此,您的Auth服务会有一个方法,您可以通过该方法说明用户已登录。Auth服务应该$rootScope注入,然后$rootScope.$broadcast()一个事件说用户已经过身份验证。然后,应用程序的其他部分可以使用$scope.$on()侦听该事件,并在用户登录时执行操作。

答案 1 :(得分:0)

如果您在服务中没有更新isLoggedIn时遇到问题,请尝试将其设为对象而不是布尔值。我在服务中双向绑定一个布尔变量有类似的问题,解决方案是让它成为一个对象的一部分。例如,您可以在服务中使用isLoggedIn和authenticatedUser属性创建Authentication对象,然后在您的服务中返回此对象。当您设置isLoggedIn和用户时,您应该在服务中看到它已更新。