[英]AngularJS: How to get $http result as returned value of a function?
[英]How to hide or show menu items when $http result returned with AngularJS
我有一個菜單和一個登錄頁面:)。
我想更改菜單項,但當前登錄后無法刷新菜單。
如果登錄成功,則應顯示某些菜單項或應添加特殊的用戶菜單項。
但是我做不到。
1)如果菜單項與$ http調用包含在同一范圍內,則可以編寫以下代碼:
function FirstController($scope, $http){
$scope.showFirstItem = false;
$scope.clickAction = function(){
$http.get('/someUrl').
success(function(data, status, headers, config) {
$scope.showFirstItem = true; //if success - show it
}).
error(function(data, status, headers, config) {
$scope.showFirstItem = false;
});
}
}
<div ng-controller="FirstController">
<button ng-click="clickAction()">Show the first item</button>
<ul>
<li ng-show="showFirstItem">First item</li>
<li>Second Item</li>
</ul>
</div>
2)如果$ http調用在另一個控制器中觸發,則可以為其創建共享服務。 您可以將某些值/操作從一個控制器傳遞給另一個控制器。
例如:
angular.module("yourAppName", []).factory("mySharedService", function($rootScope){
var mySharedService = {};
mySharedService.showFirstItem = false;
var httpCall = function() {
$http.get('/someUrl').
success(function(data, status, headers, config) {
mySharedService.showFirstItem = true;
}).
error(function(data, status, headers, config) {
mySharedService.showFirstItem = false;
});
};
mySharedService.httpCall= function(){
httpCall();
$rootScope.$broadcast('httpCallFired');
}
return mySharedService;
});
然后將其注入到任何控制器中。
function FirstController($scope, mySharedService){
$scope.showFirstItem = false;
$scope.$on('httpCallFired', function () {
$scope.showFirstItem = mySharedService.showFirstItem;
});
}
function SecondController($scope, mySharedService) {
$scope.clickAction = function() {
mySharedService.httpCall();
};
}
<div ng-controller="FirstController">
<ul>
<li ng-show="showItem">First item</li>
<li>Second Item</li>
</ul>
</div>
<div ng-controller="SecondController">
<button ng-click="clickAction()">Show the first item</button>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.