简体   繁体   中英

How to hide or show menu items when $http result returned with AngularJS

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM