Search code examples
angularjsangularjs-scopeangular-servicesangular-controller

How can I open an Angular Material menu from a controller function?


I'm doing a check for a user state and would like to enable and disable a menu accordingly.

In the markup:

<a ... ng-click="ctrl.userMenu($event)"></a>

And in the controller:

ctrl.userMenu = function (e) {
    if (ctrl.user.has.something) {
        e.preventDefault();
        return false;
    } else {
        ctrl.openMenu($mdOpenMenu, e);
    }
};

However, this doesn't trigger the menu if the else case is true. I suspect a scope issue. I've also tried wrapping the menu service call in an anonymous function. The menu opens as expected if the call is made directly from the ng-click directive. Thanks for any assistance.


Solution

  • Turns out I was forgetting to pass the menu service along with the ng-click directive:

    <a ... ng-click="ctrl.userMenu($mdOpenMenu, $event)"></a>
    // ---------------------------------^
    
    ctrl.userMenu = function (m, e) {
    // -----------------------^
        if (ctrl.user.has.something) {
            e.preventDefault();
            return false;
        } else {
            ctrl.openMenu(m, e);
            // -----------^
        }
    };