0

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");
    });
 };
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • I can't explain why theyre not automatically being destroyed, my understanding is that they would as well. The $watch function returns a a deregistration function for the listener though, so you can manually deregister the watchers when the scope is destroyed. – alexhuang Jan 09 '18 at 23:42
  • 1
    It depends on which scope these watchers are being attached to if that scope isn't being destroyed then it won't be cleaning up the watchers. https://stackoverflow.com/questions/14957614/angularjs-clear-watch – shaunhusain Jan 10 '18 at 00:42
  • Show code that opens modal – Petr Averyanov Jan 10 '18 at 09:17
  • Please see updated question – ps0604 Jan 12 '18 at 16:56
  • instead of `'vars['+i+'].obj'`, you can place a function that returns `elem.obj`, much cleaner – svarog Jan 14 '18 at 09:40

0 Answers0