角度服务和控制器共同范围
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;
});
更多相关文章
- AngularJS(1.5.8) - 如何直接从获取json对象的控制器中填充选择选
- javascript变量:全局?还是局部?这个得注意
- 如何在rails中使用ajax将数据从控制器传递到视图
- 在Javascript / node.js中共享模块之间的变量?
- Angular使用jQuery插件与外部控制器中的对象
- jQuery Ajax未能调用MVC 4控制器方法。
- 从json获取最大插槽并应用于控制器
- 求助:Python是否可以用一行代码来同时给变量赋值并打印变量的值
- Python基础(4) - 变量