0

我有一个菜单和一个登录页面:)。
我想更改菜单项,但目前我无法在登录后刷新菜单。
如果登录成功,应该显示一些菜单项或添加特殊的用户菜单项。
但我做不到。

4

1 回答 1

1

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>
于 2014-11-04T15:14:41.333 回答