从不同的控制器中隐藏我的headMenu的最佳方法

时间:2015-12-14 13:55:53

标签: angularjs ng-hide

我想隐藏我的头颅。

app.controller("kpiOverviewCtrl", function ($scope, $stateParams,) {
"use strict";

   var setUpController = function () {
       $scope.headmenu = $state.current.controller === "kpiCompareCtrl";
   };

   $rootScope.$on('$locationChangeSuccess', function () {
       setUpController();
   });

   $rootScope.$on('$stateChangeSuccess', function () {
       setUpController();
   });

   setUpController();
});

正如您在代码中看到的那样,它在控制器交换机上将headmenu设置为true。它工作正常。但是现在我想要从已经加载的控制器的headmenu语句中将ng-click设置为true。

app.controller("kpiDetailsCtrl", function ($scope, $state) {
"use strict";

 $scope.loadDataForMonthView = function () {
    $scope.errorNoDataForDate = false;
    $scope.yearMode = false;
    $scope.monthMode = true;

    //Here I want to set $scope.headmenu = true;

   //Other code.....
};

有什么好建议吗?

3 个答案:

答案 0 :(得分:1)

使用广播。它们是控制器之间通信的绝佳方式。

在主控制器中创建常规功能,您可以从控制器本身调用该功能。

app.controller('Main', function($scope) {
    function setHeadMenu() {
         // Set menu to true
    }

    $scope.$on('setHeadMenu', function() {
        setHeadmenu(); // Fires on broadcast
    })
});

创建一个ng-click,用于从其他控制器激发广播

app.controller('Second', function($scope) {
    $scope.click = function() {
        $scope.$broadcast('setHeadMenu'); // Send a broadcast to the first controller
    }
});

答案 1 :(得分:0)

第一个假建议:

$scope.loadDataForMonthView = function () {
 $scope.headmenu = true; //(or false)
}

但很可能你正在使用一些异步调用,所以这样的事情会更好:

$scope.loadDataForMonthView = function () {
 // First: you need some promise object
 // the most simple is to use $http
 var promise = $http({url: 'some.url', method: 'GET'});

 promise.then(function() {
  // the data have arrived to client
  // you can hide or show menu according to your needs
  $scope.headmenu = true; //(or false)
 })
}

有关$http工作原理的更多信息,请参阅文档https://docs.angularjs.org/api/ng/service/ $ http

答案 2 :(得分:0)

您可以在kpiOverviewCtrl中向$ rootScope声明新方法:

app.controller("kpiOverviewCtrl", function ($scope, $stateParams, $rootScope) {
     "use strict";
     //your code...........
     $rootScope.setUpController = setUpController;   
});

然后从kpiDetailsCtrl控制器调用它:

app.controller("kpiDetailsCtrl", function ($scope, $state, $rootScope) {
"use strict";

 $scope.loadDataForMonthView = function () {
        $scope.errorNoDataForDate = false;
        $scope.yearMode = false;
        $scope.monthMode = true;

        $rootScope.setUpController();
    }
});