AngularJS Scope.on和Scope.emit在筛选器中的调用顺序

AngularJS Scope.on and scope.emit calling order in a filter

本文关键字:Scope 顺序 调用 on emit AngularJS 筛选      更新时间:2023-12-26

在我的一个过滤器中,监视在另一个控制器中更改的值。根据更新后的值,我想决定是否应该调用emit。如下所示。

scope.$on('XChanged', function(event, x) {
              console.error( '==order list has changed : ' + x  );
              console.warn('INSIDE FILTER ON '+event);
             scope.bx = true; // bx variable is initialized in the controller where the filter is called and default is false.
            });
          console.warn('AFTER FILTER ON 1 >>'+ scope.bx);
           if( !scope.bx  ){
             scope.$emit('handleEmit', {msg: 'RECYCLE' });
             console.error( scope.bx+ ' Recycle requested. ');
           }

但问题是,scope.on是首先执行的,并且在过滤器中不会从上到下执行。此外,即使bx在scope.on中被设置为true,if( !scope.bx )也变为true,这意味着分配给bx的true值没有被设置。。。可能是我走错了路。。。你能告诉我怎么才能想出这个主意吗。我只想做的是,根据scope.on中更改的值,应该执行emit。(换句话说,bx布尔值在scope.on中发生了更改,bx的更新值应该能够决定是否应该执行emit。)

我认为您需要使用$watch。

    scope.$on('XChanged', function(event, x) {
         console.error( '==order list has changed : ' + x  );
         console.warn('INSIDE FILTER ON '+event);
         scope.bx = true; // bx variable is initialized in the controller where the filter is called and default is false.
        });
         console.warn('AFTER FILTER ON 1 >>'+ scope.bx);
    scope.$watch('bx', function(newVal, oldVal){
        if (newVal == oldVal)
            return; //shit happens ;-)
         if( !scope.bx  ){
           scope.$emit('handleEmit', {msg: 'RECYCLE' });
           console.error( scope.bx+ ' Recycle requested. ');
         }
    });