I have AuthService and want to use this service in some controllers.

我有AuthService并希望在某些控制器中使用此服务。

I want to show or hide "log out" button in my front-end, depends on $scope.isLoggedIn.

我想在我的前端显示或隐藏“注销”按钮,取决于$ scope.isLoggedIn。

My front-end code:

我的前端代码:

<md-button ng-if="isLoggedIn" class="md-button" ng-click="signOut()" aria-label="Logout">
    Logout
</md-button>

and my signOut() function:

和我的signOut()函数:

$scope.signOut = function() {
    AuthenticationService.signOut().then(function() {
        $location.path('/');
    });
};

Authentication service contains functions: signIn(), signOut() and field .isLoggedIn = true|false.

身份验证服务包含以下函数:signIn(),signOut()和field .isLoggedIn = true | false。

And I want to update my variable in controller, $scope.isLoggedIn depends on AuthenticationService.isLoggedIn. But if I try this:

我想在控制器中更新我的变量,$ scope.isLoggedIn依赖于AuthenticationService.isLoggedIn。但如果我试试这个:

$scope.isLoggedIn = AuthenticationService.isLoggedIn

it works OK, but only when I load site. So if user is logged in, variable $scope.isLoggedIn is true and if user isn't logged in variable $scope.isLoggedIn is false.

它工作正常,但只有当我加载网站。因此,如果用户已登录,则变量$ scope.isLoggedIn为true,如果用户未登录,则变量$ scope.isLoggedIn为false。

But if AuthenticationService.isLoggedIn change while application runs it doesn't change $scope.isLoggedIn.

但是,如果AuthenticationService.isLoggedIn在应用程序运行时发生更改,则不会更改$ scope.isLoggedIn。

Is it possible to keep this reference between service and controller? Or should I do this in another way?

是否可以在服务和控制器之间保留此参考?或者我应该以另一种方式做到这一点?

3 个解决方案

#1


1

use also $watch in controller

在控制器中也使用$ watch

$scope.$watch(function(){return AuthenticationService.isLoggedIn}, function(newval, oldval){
   $scope.isLoggedIn = newval;
});

更多相关文章

  1. AngularJS(1.5.8) - 如何直接从获取json对象的控制器中填充选择选
  2. javascript变量:全局?还是局部?这个得注意
  3. 如何在rails中使用ajax将数据从控制器传递到视图
  4. 在Javascript / node.js中共享模块之间的变量?
  5. Angular使用jQuery插件与外部控制器中的对象
  6. jQuery Ajax未能调用MVC 4控制器方法。
  7. 从json获取最大插槽并应用于控制器
  8. 求助:Python是否可以用一行代码来同时给变量赋值并打印变量的值
  9. Python基础(4) - 变量

随机推荐

  1. 即使通过一系列图像预先加载也表现不佳
  2. 返回指定时间段相同间隔数组
  3. JavaScript 中的相等性判断
  4. 前端文件上传原理
  5. 通过Angular Factory过滤,切片,排序Javascr
  6. javascript添加两个文本框值,并在asp.net
  7. $ postLink的角度组件/指令运行得太早
  8. 如何在Sencha Touch中向模型添加自定义验
  9. js获取点击事件的位置,兼容主流浏览器
  10. JavaScript 基础回顾——对象