Emil Gurbanov Emil Gurbanov - 26 days ago 6
AngularJS Question

Changing controller variable from directive and passing it to ng-show - Angular JS

I need to change a controller variable from a directive and then pass its updated value to ng-show. Please see my code below:

Controller:

self.menuVisible = false;


Directive:

icon.bind('click', function(){
scope.menuCtrl.menuVisible = true;
})


NOTE: there are lot more code lines in the directive which are not relevant to the question, and this is the reason why I use directive instead of controller function which I could pass with ng-click.

View:

<div class="menu-item" ng-show="menuCtrl.menuVisible"></div>
<div class="icon" my-directive></div>


Although nothing visible happens on the element click, when I check the menuCtrl.menuVisible in devtools it returns true after the action.

Could you please explain what I am doing wrong?

Thanks in advance!

Answer

Most likely you're not updating your variable inside $digest loop, try like this:

icon.bind('click', function(){
    $scope.$apply(function() {
        scope.menuCtrl.menuVisible = true;
    }
})