Search code examples
javascriptangularjsbroadcast

$broadcast gets called multiple times on ng repeat, even if called once from controller


Controller onSuccess

function onSuccess(data) {
                        vm.myData = true;
                        $scope.$broadcast('showGood',{index});
                    }

Directive

function myDir($document) {
        return {
            restrict: 'A',
            scope: {

                index: '=',

            },
            link: function (scope, element, attrs) {
                scope.showGood = function(){
                  scope.selectedIndex = scope.index;
                  //DOM Manipulation
                  scope.$apply();
                };
                scope.$on('showGood',function(event, data){
                  console.log("event triggered - showGood" + data.index); // ---> Getting called as many no of times as ng repeat elem
                  event.preventDefualt();
                  event.stopPropagation();
                  if(data.index === scope.index) {
                    scope.showGood();
                  }

                });

html -

ng-repeat - div and a button with ng-click ->

 <div my-dir index="$index" ng-click = "onSuccess()" class="btn-div" title="Click">

$broadcast gets called multiple times. How to prevent it? Writing destroy, doesn't do trick of $apply for DOM manipulation now.

Thanks


Solution

  • Its happening you are using your directive inside ng-repeat and subscribe to showGood nth time due to ng-repeat

    Solution is append index something like

    Controller

               function onSuccess(index,data) {
                            vm.myData = true;
                            $scope.$broadcast('showGood'+index,{index});
                        }
    

    HTML

    <div my-dir index="$index" ng-click = "onSuccess($index)" class="btn-div" title="Click">
    

    Directive

    function myDir($document) {
            return {
                restrict: 'A',
                scope: {
    
                    index: '=',
    
                },
                link: function (scope, element, attrs) {
                    scope.showGood = function(){
                      scope.selectedIndex = scope.index;
                      //DOM Manipulation
                      scope.$apply();
                    };
                    scope.$on('showGood'+scope.index,function(event, data){
                      console.log("event triggered - showGood" + data.index); // ---> Getting called as many no of times as ng repeat elem
                      event.preventDefualt();
                      event.stopPropagation();
                      if(data.index === scope.index) {
                        scope.showGood();
                      }
    
                    });
    

    Working demo