我有一个带有登录按钮的布局页面,我只想在我未登录时显示它。我想通过使用服务来实现:
app.service('AuthService', function ($http) {
this.getUserStatus = function () {
return $http({
url: '/auth/status',
method: "GET"
});
};
});
然后我在 Controller 中这样调用它:
app.controller('MenuController', [
'$scope',
'$http',
function ($scope, AuthService) {
$scope.authorize = function() {
AuthService.getUserStatus();
}
}
]);
最后,我在布局中使用 ng-controller 和 ng-hide 来显示或隐藏注销按钮:
<body ng-app="headcountApp">
<nav ng-controller="MenuController">
<ul>
<li ng-hide="authorize">
<a href="#/">Login</a>
</li>
<li>
<a href="#/employee/add">Add</a>
</li>
<li>
<a href="#/employees">employees</a>
</li>
<li>
<a href="#/edit">Edit</a>
</li>
<li>
<a href="#/delete">Delete</a>
</li>
<li>
<a href="/logout">logout</a>
</li>
</ul>
</nav>
我的问题是它总是隐藏的,告诉我这个值总是正确的。我该如何解决这个问题?
这解决了问题:
app.controller('MenuController', [
'$scope',
'$http',
'AuthService',
function ($scope, $http, AuthService) {
$scope.authorized = false;
AuthService.getUserStatus().then(function(res){
$scope.authorized = res.data;
});
}
]);
最佳答案
AuthService.getUserStatus();
返回 $http() 的结果. $http()
调用的结果是 promise .您需要注册一个 resolve 回调并 promise 获取 http 请求的结果:
$scope.authorized = false;
$scope.authorize = function() {
AuthService.getUserStatus().then(function(res){
// If result from server indicate login state set $scope.authorized = true
});
}
并在您的 View 中绑定(bind)到 $scope.authorize
:
<li ng-hide="authorized">
<a href="#/">Login</a>
</li>
关于javascript - 从 Controller Angular ng-hide 中的服务调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41855204/