Reputation: 329
I have a menu and a login page :).
I want to change the menu item but currently I can't refresh menu after login.
If login succeeds, some menu items should display or special user menu items should be added.
But I can't to do it.
Upvotes: 0
Views: 1193
Reputation: 6962
1) If your menu's items contain in the same scope with the $http call, you can write the following code:
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) If the $http call fired in the other controller, you can create shared service for it. You can pass some values/actions from one controller to another.
For example:
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;
});
And after to inject it into any controller.
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>
Upvotes: 1