Thanh Trung Thanh Trung - 3 months ago 13
jQuery Question

AngularJS digest inside a function

Supposedly I have the following HTML

<div ng-if="running">
<div id="someid"></div>
</div>
<span ng-click="myfunc">Click</span>


In angular controller I set a function when click a button

$scope.myfunc = function(){
$scope.running = true;

//attach some jquery event
$('#someid').on('animationend', function(){...})
}


I want to update the DOM right after
running=true
because if I dont or put the attached event somewhere else, it doesn't work because the DOM didnt exist yet.
ng-if
seems to remove it and it only shows the div only when the function ends. I tried
$scope.$digest()
right after running not work either and it shows error.

So what's the proper way to attach the event above?

Answer

Try using $timeout in your controller, in this way:

    myApp.controller('exampleController', ['$scope', '$timeout', function($scope, $timeout) {

                $scope.myfunc = function(){
                   $scope.running = true;            

                   var timeout = $timeout(function({
                     $('#someid').on('animationend', function(){...})  

                     $timeout.cancel(timeout);  
                   }, 0)
                }
            }]);

Shortly speaking, $timeout with 0 as interval lets you to wait for the next digest cycle.