I have a Model that is periodically changed. Every time it is changed and view is rerendered (according to bindings) I need to execute some jQuery code. What is the right place to put this code?
Asked
Active
Viewed 140 times
0
-
in a ng-change function – SoluableNonagon Sep 17 '14 at 17:29
-
also, you could also use directives (preferred) for DOM changes; which is the preferred method and set up a watcher there. – SoluableNonagon Sep 17 '14 at 17:33
-
out of curiosity, what jQuery code do you run? – SoluableNonagon Sep 17 '14 at 17:34
1 Answers
0
If the change happens say, in an input field
<input ng-change="runThis()" ng-model='mymodel'/>
$scope.runThis = function(){ /*do something*/ };
If the change can happen anywhere you can just create a watcher:
$scope.$watch('mymodel', function(newVal, oldVal){
if(newVal){ // do nothing if undefined or null
// do something
$timeout(function(){ // dont forget to inject $timeout into controller
// fire function after one second
}, 1000);
}
});

SoluableNonagon
- 11,541
- 11
- 53
- 98
-
Is it specified that my custom watch is executed after bindings are rerendered? – SiberianGuy Sep 17 '14 at 17:47
-
the watch is executed any time the scope variable changes. so if you have $scope.myModel then you should watch like so: $scope.$watch('myModel', ...); – SoluableNonagon Sep 17 '14 at 17:49
-
Yeah, but I need to exeucte jQuery code (some plugins) after bindings are updated (html is rerendered) – SiberianGuy Sep 17 '14 at 17:55
-
Well, you won't really know when it's completely re-rendered that I know of, the best you can do is do a $timeout to fire the jQuery code after some set of time. – SoluableNonagon Sep 17 '14 at 18:00
-
same issue here http://stackoverflow.com/questions/12304291/angularjs-how-to-run-additional-code-after-angularjs-has-rendered-a-template – SoluableNonagon Sep 17 '14 at 18:04