即使从控制器调用一次,也会在ng repeat上多次调用$ broadcast

时间:2017-11-10 09:27:17

标签: javascript angularjs broadcast

控制器 的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被多次调用。怎么预防呢?写破坏,现在没有申请DOM操作的技巧。

由于

1 个答案:

答案 0 :(得分:1)

它正在发生你在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