I have the following code in a directive. The directive is included in an Angular UI modal:
var watchObjects = function(){
scope.vars.forEach(function(elem,i){
scope.$watch('vars['+i+'].obj', function(newValue, oldValue) {
if (typeof newValue === 'undefined')
return;
console.log(newValue)
});
});
};
When the modal is opened and the directive is loaded, in the link function I invoke watchObjects
only the fist time I open the modal. If I call watchObjects
every time I open the modal, the number of watch functions starts accumulating (instead of being invoked once when the object changes, the function is invoked N times where N represents the number of times the modal was opened). Why may this happen? Shouldn't the watchers be destroyed when the modal is closed? If not, is there a way to destroy the watchers manually?
UPDATE
I have the same problem when registering $on
to receive broadcasted messages. I need to run watchCancel
only the first time I open the modal, otherwise the message will be received N times.
var watchCancel = function(){ // I need to invoke this function only once
scope.$on("cancel",function(event,data){
alert("cancelled");
});
};