Thanh Trung Thanh Trung - 1 year ago 79
jQuery Question

AngularJS digest inside a function

Supposedly I have the following HTML

<div ng-if="running">
<div id="someid"></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
because if I dont or put the attached event somewhere else, it doesn't work because the DOM didnt exist yet.
seems to remove it and it only shows the div only when the function ends. I tried
right after running not work either and it shows error.

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

Answer Source

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(){...})  

                   }, 0)

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

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