Filippo oretti
Filippo oretti

Reputation: 49813

Angularjs - Broadcast event is double fired

I have this simple code:

<modal ng-controler="Contacts">
//add new contact stuffs
</modal>

<div ng-controller="Contacts">
// show the new contact when added
</div>

.controller('Contacts', function ($scope, contactsFactory) {

contactsFactory.doSomething();
$scope.$on('contacts:addedNewContact', function (event, data) {

      console.log('yo');
});
})
.factory('contactsFactory', function ($rootScope) {
var addNew = function (username, email) { //facoltative, we can get them via email OR username

          return $http({
            'method':'POST',
            'url': appWS + '/api/contact',
            'data': {
              'email':email,
              'username':username
            }
          }).then(function (response) {

            if (response && response.status === 200) {

              $rootScope.$broadcast('contacts:addedNewContact', response.data);
            }

          }).catch(function (err) {

            $rootScope.$broadcast('contacts:errorAddingNewContact');
            $window.console.error('Error while retrieving contact user data: ' + err);
          });
        };

    return {
      'addNew':addNew
    };
});

The broadcast contacts:addedNewContact actually is putting 2 times "yo" in console.

I cant understand why it gets double fired instead of only 1 time.

Any help appreciated, thanks

Upvotes: 2

Views: 1676

Answers (1)

eekboom
eekboom

Reputation: 5802

You have two divs that use the controller, so it is instantiated twice, registers the listener twice, and both listeners will be triggered.

Upvotes: 2

Related Questions