Thomas Dittmar
Thomas Dittmar

Reputation: 1924

Manage ng-if from another controller

I have prepared a Plunkr that provides the code:

https://plnkr.co/edit/WXtQxVcdgyvnaajbs4eJ?p=preview

I have assigned the object $scope.menu.show in controller toolbarCtrl that controls whether the menu is created or not.

<md-menu id="menu" ng-controller="toolbarCtrl" ng-if="true"> ...

When toolbarCtrl gets initialized I can control whether the menu is shown but I would like to control it from another controller. In this case I created two buttons in mainCtrl that produce true or false and I'm trying to assign the value to the $rootScope but that doesn't work.

How can I do that?

UPDATE: Although jtmingus solution works perfectly I came up with another solution that doesn't need events.

I created this factory service:

app.factory('menuState', function () {
  var state = {val: false};
  function getState() {
    return state;
  }
  function setState(newState) {
    state.val = newState;
  }
  return {
    getState: getState,
    setState: setState
  }
});

Then at the toolbarCtrl controller I initially hide the menu

app.controller('toolbarCtrl', function($scope, menuState) {
  // hide the menu
  menuState.setState(false);

  // pass the value to the menu
  $scope.state = menuState.getState();
});

on the mainCtrl I define the button clicks like that:

app.controller('mainCtrl', function($scope, $rootScope, menuState) {
   $scope.state = menuState.setState;
});

and 2 buttons on the the main.html

<md-button class="md-primary md-raised" ng-click="setState(true)">Show</md-button>
<md-button class="md-primary md-raised" ng-click="setState(false)">Hide</md-button>

Upvotes: 0

Views: 546

Answers (2)

jtmingus
jtmingus

Reputation: 834

The way that data generally should be shared through controllers is by using a service. Because you need both controllers to watch the same state, you can use Angular's events, specifically the $on event.

Here is an article that will walk you through having multiple controllers watch the same state:

https://variadic.me/posts/2013-10-15-share-state-between-controllers-in-angularjs.html

Edit: After looking through this article some more, I realized it's not the best explanation, and there are some things in the code that don't work. For example, if you try to pass arguments in with a $broadcast call, the $on function needs two paramaters–event and args.

Upvotes: 1

gmuraleekrishna
gmuraleekrishna

Reputation: 3431

On the controller from which you want to initiate showing the menu,

app
.controller('MainCtrl', ['$scope', function($scope) {
     $scope.$broadcast('menu:show');
}])
.controller('ToolbarCtrl', ['$scope', function($scope) {
     var ToolbarCtrl = this;
     $scope.$on('menu:show', function() {
        ToolbarCtrl.showMenu = true;
     });
}])

In the markup switch using this value

<md-menu id="menu" ng-controller="ToolbarCtrl" ng-if="ToolbarCtrl.showMenu"> ...

Upvotes: 1

Related Questions