3gwebtrain
3gwebtrain

Reputation: 15303

angular `$broadcast` issue - how to fix this?

In my app, I am boradcasting a event for certain point, with checking some value. it works fine But the issue is, later on whenever i am trigger the broadcast, still my conditions works, that means my condition is working all times after the trigger happend.

here is my code :

scope.$watch('ctrl.data.deviceCity', function(newcity, oldcity) {

    if (!newcity) {
        scope.preloadMsg = false;
        return;
    }

    scope.$on('cfpLoadingBar:started', function() {
        $timeout(function() {
            if (newcity && newcity.originalObject.stateId) { //the condition not works after the first time means alwasy appends the text
                console.log('each time');

                $('#loading-bar-spinner').find('.spinner-icon span')
                    .text('Finding install sites...');
            }
        }, 100);
    });
});

Upvotes: 0

Views: 57

Answers (1)

vileRaisin
vileRaisin

Reputation: 1222

you can deregister the watcher by storing its reference in a variable and then calling it:

   var myWatch = scope.$watch('ctrl.data.deviceCity', function(){
          if( someCondition === true ){
                 myWatch(); //deregister the watcher by calling its reference
          }
   });

if you want to switch logic, just set some variable somewhere that dictates the control flow of the method:

var myWatch = scope.$watch('ctrl.data.deviceCity', function(){
     scope.calledOnce = false;

     if(!scope.calledOnce){
        //... run this the first time
        scope.calledOnce = true;
     }
     else {
        // run this the second time (and every other time if you do not deregister this watch or change the variable)
        // if you don't need this $watch anymore afterwards, just deregister it like so:
        myWatch();
     }
})

Upvotes: 1

Related Questions