I have an angular app, in which a model
change triggers a pop-up which is a directive
. I need to select an element on this pop-up, but the DOM update ('$digest') seems to be asynchronous and as a result it doesn't work for the first time the pop-up is shown/created. This works for subsequent pop-ups. How do I make sure that my code runs after the pop-up has been created and rendered with all the child elements?
Here is the equivalent code:
angular.module('mymodule', []).directive('myDirective', function() {
return {
require: ngModel,
link: function($scope, element, attrs, ctrl) {
element.addClass('foo');
// And similar stuff
ctrl.$render = function justRender() {
if (ctrl.viewValue) {
element.modal('show');
/* Here I have code for selecting the contents of the pop-up,
which doesn't work as DOM is not assuredly rendered at this time.
*/
} else {
element.modal('hide');
}
}
}
}
});
You could use the $timeout
service of AnguarJS at this purpose.
So you have to wrap your code in a callback... something like:
$timeout(function() {
// your code here
}, 0);
$timeout
is an AngularJS wrapper for the window.setTimeout
. It adds a new event in the browser event queue; since the rendering engine is already in this queue, the browser will complete page rendering before processing a new task in the queue.
I wrote an article on my blog about this topic... you could use it as reference when you need to run code after DOM has been rendered .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.