繁体   English   中英

AngularJS返回$ http结果时如何隐藏或显示菜单项

[英]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.

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