从控制器中的服务调用函数 angular ng-hide
Calling function from service in controller angular ng-hide
我有一个带有登录按钮的布局页面,我只想在未登录时显示它。我想通过使用服务来实现:
app.service('AuthService', function ($http) {
this.getUserStatus = function () {
return $http({
url: '/auth/status',
method: "GET"
});
};
});
然后我在控制器中这样调用它:
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();
return $http(). the result of $http()
call is a promise 的结果。您需要使用 promise 注册一个解析回调以获取 http 请求的结果:
$scope.authorized = false;
$scope.authorize = function() {
AuthService.getUserStatus().then(function(res){
// If result from server indicate login state set $scope.authorized = true
});
}
并且在您看来绑定到 $scope.authorize
:
<li ng-hide="authorized">
<a href="#/">Login</a>
</li>
我有一个带有登录按钮的布局页面,我只想在未登录时显示它。我想通过使用服务来实现:
app.service('AuthService', function ($http) {
this.getUserStatus = function () {
return $http({
url: '/auth/status',
method: "GET"
});
};
});
然后我在控制器中这样调用它:
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();
return $http(). the result of $http()
call is a promise 的结果。您需要使用 promise 注册一个解析回调以获取 http 请求的结果:
$scope.authorized = false;
$scope.authorize = function() {
AuthService.getUserStatus().then(function(res){
// If result from server indicate login state set $scope.authorized = true
});
}
并且在您看来绑定到 $scope.authorize
:
<li ng-hide="authorized">
<a href="#/">Login</a>
</li>