2

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

itsme
  • 48,972
  • 96
  • 224
  • 345

1 Answers1

2

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

eekboom
  • 5,551
  • 1
  • 30
  • 39
  • Also avoid using $rootScope.$broadcast, it will push the event through all active scopes and can be pretty horrible performance-wise. Instead use $rootScope.$emit and $rootScope.$on. – Lowe Bäckström Oct 08 '14 at 11:42
  • ok but registering 2 times some event listner is not really the solution i guess i have to use a directive so dunno – itsme Oct 08 '14 at 12:20
  • i will move logic on a directive i guess , thank you – itsme Oct 08 '14 at 12:28