Search code examples
angularjsangularjs-controller

Call more than 1 $rootScope.$on


Hey I am trying to execute one portion of code only if there is 2 $broadcast event, this is what I got.

In my controller1 I have this.

$rootScope.$broadcast('receivedData');

In my controller2

$rootScope.$broadcast('dataLoaded');

So far I have this.

$rootScope.$on('dataLoaded',function(){
    $http({
       url:"http://api/data",
       method:"POST",
       data:{id_cliente: parseInt(getVariable("id"))},
       headers:{
             "Content-Type":"application/json;charset=utf-8",
             "Authorization" : "Bearer " + getVariable("token")
     }
   })
     .then(function(response){
           setVariable("contratos", JSON.stringify(response.data));
           $rootScope.$broadcast("cargaContratos");

   },
     function(response){
     });
})

And I have to execute this only if recievedData and dataLoaded are triggered. Anybody knows how to do it?


Solution

  • Maybe you can do something like this:

    var received = [];
    
    $rootScope.$on('receivedData', function() {
        received.push('receivedData');
        doSomething();
    })
    $rootScope.$on('dataLoaded', function() {
        received.push('dataLoaded');
        doSomething();
    })
    
    doSomething() {
        if (received.indexOf('receivedData') > -1 && received.indexOf('dataLoaded') > -1) {
            // Your code here
        }
    }
    

    I'd recommend using services/promises though, AngularJS has a promise library included by default: $q. Then, you can simply use $q.all(). But for now, this should work fine.


    Update (promise example)

    Actually, you already use a promise ($http), which enables a callback with then().

    Here is a (copy-pastable) example of a simple promise setup. You should try it out:

    Service:

    app.service('promiseTest', function($q) {
        this.myPromise = function() {
            return $q(function(resolve, reject) {
                setTimeout(function() {
                    resolve('hello!');
                }, 1000);
            });
        }
    })
    

    Component/Controller:

    app.controller('promiseTestCtrl', function(promiseTest) {
        promiseTest.myPromise().then(function(msg) {
            console.log(msg)
        })
    })
    

    I recommend playing around with them to understand them better.

    When both calls are converted to a promise, you can then use:

    var promises = [myService.receivedData, myService.dataLoaded];
    
    $q.all(promises).then(function() {
        // Your code
    })