angular` $ broadcast`问题 - 如何解决这个问题?

时间:2016-08-29 15:58:47

标签: angularjs

在我的应用中,我boradcasting是某个特定点的事件,并检查了一些值。它工作正常但问题是,以后每当我触发broadcast时,我的条件仍然有效,这意味着我的状况在trigger发生后一直有效。

这是我的代码:

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);
    });
});

1 个答案:

答案 0 :(得分:1)

您可以通过将其引用存储在变量中然后调用它来取消注册观察者:

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

如果你想切换逻辑,只需在某个地方设置一个指示方法控制流程的变量:

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();
     }
})