Mehdi
Mehdi

Reputation: 368

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

Upvotes: 0

Views: 347

Answers (1)

devonj
devonj

Reputation: 1238

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

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

Basically when you emit the event and your controller catches it and sets $scope.show 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: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Upvotes: 2

Related Questions