Darko Romanov
Darko Romanov

Reputation: 2805

AngularJS controllers communication

I'm not sure I'm doing what I need in the right way... I have 2 controllers:

SiteMenuCntl and DashboardCntl

SiteMenuCntl is bound to a UL tag, and it's the menu of the site. By default it's hidden, and after credentials verification and the DashboardCntl is loaded the menu should come visibile.

I tried this:

app.controller('SiteMenuCntl', ['$scope', 'site', 'security', '$log', function ($scope, site, security, $log) {
    $scope.visibility = "hidden";
    $scope.$on('showTree', function () {
        console.log("event fired"); //never fired :-(
        $scope.visibility = "";
    });
}]);

app.controller('DashboardCntl', ['$scope', function ($scope) {
    $scope.$emit('showTree');
}]);

but the event showTree is never fired. Where am I doing wrong? Is there a better way to do that?

Upvotes: 0

Views: 168

Answers (2)

Kevin Stone
Kevin Stone

Reputation: 8981

I'm guessing your SiteMenuCntl is down the scope tree from the DashboardCntl so when $emit triggers upwards (towards $rootScope), it doesn't reach SiteMenuCntl.

Try using $rootScope.$broadcast('showTree') instead. That triggers from the top of the tree downwards through any listening scopes.

Upvotes: 1

pythonian29033
pythonian29033

Reputation: 5207

there's a way easier way to do this;

why don't you set a boolean $scope.showSiteMenuCntl=false; in your controller and then when you want to show it you go $scope.showSiteMenuCntl=true;

and then in your html you go;

<ul ng-controller="SiteMenuCntl" ng-show="showSiteMenuCtrl"></ul>

Upvotes: 0

Related Questions