Angular Interop Example - How update the model and refresh the view from legacy outside code by calling $apply()

12,721 views
Skip to first unread message

Johno Scott

unread,
Jul 30, 2012, 9:54:28 PM7/30/12
to ang...@googlegroups.com
I spent a day understanding this so thought I would share :

Am I doing the right thing here ?

Q. How do you update your Angular model from outside code ?

A. If you know the DOM element that contains your Angular model's scope you can call a controller method via $apply() which will refresh the view automatically :

    // get Angular scope from the known DOM element
    document.getElementById('myAngularApp');
    scope angular.element(e).scope();
    // update the model with a wrap in $apply(fn) which will refresh the view for us
    scope.$apply(function({
        scope.controllerMethod(val);
    }); 

Example: This example shows how an interval timer can send repeated updates to the Model by getting the scope and then calling my controllers MainCtrl.setTicks() method from within scope.$apply()


References :


j...@fotobabble.com

unread,
Jul 31, 2012, 4:53:21 PM7/31/12
to ang...@googlegroups.com
Thanks very much for the scope.$apply example!  It's exactly what I needed after confirming a jquery modal dialog I changed the model, but it was not updating the view instantly.  Wrapping it in the $apply allowed it to change instantly.
Reply all
Reply to author
Forward
0 new messages