Dittmar Consulting Dittmar Consulting - 1 year ago 75
AngularJS Question

Manage ng-if from another controller

I have prepared a Plunkr that provides the code:


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?

Answer Source

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:


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.