search

Home  >  Q&A  >  body text

angular.js - angularjs如何同时监听两个以上的事件?

业务场景描述:

假设在子controller中,用户各种点击操作会被分成两个事件,被控制器广播到父控制器中

$scope.$emit('ngUserLogin');
$scope.$emit('ngUserUpdate');

在父控制器中,我们使用$on监听这两个事件没错,

$scope.$on('ngUserlogin', function(){"}
$scope.$on('ngUserUpload', function(){"}

但是在某个场景中,我发现这两个事件的执行的是相同的逻辑,所以我想这样写:

$scope.$on(['ngUserlogin','ngUserUpload'], function(){"}

这是我期望的模式,但是ng很明显是不能这么写的,想问问各位大侠在自己的实际业务中如何做到同时监听两个以上的事件

PHPzPHPz2744 days ago542

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-15 17:05:07

    It’s a pity that ng does not have the mode you expected. To make a little trick, you can write like this:

    angular.forEach(['ngUserlogin','ngUserUpload'], function(value){
        $scope.$on(value, function(event){
            console.log(event.name);//执行你想要的吧
        });
    });

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-15 17:05:07

    You can change your thinking, you only send one event, and then bring different parameters when sending this event$emit(name, args);; when you listen to this event, judge the parameters, and you will know what you want to do next.

    reply
    0
  • Cancelreply