当前位置: 代码迷 >> JavaScript >> Angular指令单击函数调用两次
  详细解决方案

Angular指令单击函数调用两次

热度:37   发布时间:2023-06-07 11:40:26.0

以下是两个指令。 我的问题是我的第二个指令中的函数addSectorAttributes在来自project_subtypes.html的ng-click上被触发了两次。

      .directive('projectFilter', function($compile, $timeout){
            return {
                restrict: 'E',
                templateUrl: 'project_filter.html',
                link : function(scope,element, attr){
                   //getting data and fill the html from a service 
                },
                controller: function ($scope) {
                    $scope.addSubTypes = function (event,id) {
                      var ex = $(event.currentTarget);

                      var el = $compile( "<project-subtypes typeid="+id+" class='slide-content'></project-subtypes>" )( $scope );
                        ex.parent().append(el);

                    };
                }
            }
        })

       .directive('projectSubtypes', function($compile){
                return {
                    restrict: 'E',
                    scope: true,
                    templateUrl: 'project_subtypes.html',
                    link : function(scope,element,attr){
                            //getting data and fill the html from a service
                           var id = attr.typeid; 
sectorFiltering.getSectorSubTypes(id).success(function(data) {
                        scope.sector_subtypes = data.sector_subtypes;
                    });
                        });
                    },
                    controller: function ($scope) {
                        $scope.addSectorAttributes = function (event,id) {
                            console.log("teeest"); // called twice.....
                        };
                    }                        
                }
            })

project_subtypes.html

<li ng-repeat="subtype in substype.subtypes">
        <div layout='row' class='load-attributes' ng-click=" addSectorAttributes($event, subtype.id)"></div>
 </li>

请帮忙....

如果指令函数调用两次,如果一次它没有给你subtype.id,下次如果它给你subtype.id那么你只需要在你的指令中添加条件,如下所示。

subtype.id && addSectorAttributes($ event,subtype.id)“

此致,Mahenrdra