$broadcast 在 ng 重复时被多次调用,即使从控制器调用一次

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

控制器 onSuccess

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

指令

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 被多次调用。如何预防?写 destroy,现在不会做 $apply for DOM 操作的技巧。

谢谢

你正在 ng-repeat 中使用你的指令并由于 ng-repeat

第 n 次订阅 showGood

解决方案是附加索引,例如

控制器

           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">

指令

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