Mehdi Guelloub Mehdi Guelloub - 1 year ago 97
AngularJS Question

AngularJS emit event from directive and update the DOM

I looked in the internet before asking this question but i couldn't find the right answer.

So, I want to emit an event from a directive to a controller and when this event occurs I want to update the DOM. I made a dummy plunker please check it out.

When I emit the event, the controller notice that but he didn't update the DOM. Please, see the console when firing the event.

Can anyone explain to me?
Thank you

Answer Source

You need to wrap a $scope.$apply around your $ = true like:

$scope.$apply(function() {
    $ = true;

Basically when you emit the event and your controller catches it and sets $ to true, the logic happens outside of Angular's digest cycle. Since the digest cycle does not see the update, it does not update the DOM.

$scope.$apply explicitly tells Angular: "hey I've updated this variable, check it out and update the DOM for me"

More information and pretty good explanation here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download