search

Home  >  Q&A  >  body text

angular.js - How to listen to more than two events at the same time in angularjs?

Business scenario description:

Assume that in the child controller, the user's various click operations will be divided into two events, which will be broadcast to the parent controller by the controller

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

In the parent controller, we use $on to listen to these two events, yes,

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

But in a certain scene, I found that these two events executed the same logic, so I wanted to write it like this:

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

This is the mode I expected, but ng obviously cannot be written like this. I would like to ask you how to monitor more than two events at the same time in your actual business

PHPzPHPz2847 days ago597

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