简体   繁体   English

角度指令编译器两次触发 ng-click

[英]angular directive compiler fired ng-click twice

I am using accordion directive in my template, and inside accordion i am adding attr ng-click on a element.我在模板中使用了手风琴指令,在手风琴中,我在元素上添加了attr ng-click When I click on that element it fires twice.当我单击该元素时,它会触发两次。

Fiddle : http://jsfiddle.net/Lvc0u55v/10071/小提琴: http : //jsfiddle.net/Lvc0u55v/10071/

Code :代码 :

//accordion directive
.directive('simpleAccordion', function($compile, $timeout) {
    return {
        restrict: 'AEC',
        controller: function($scope) {
            $scope.current = null;
            $scope.height = [];
            $scope.zero = {
                height: 0
            };
            $scope.toggle = function(i) {
                $scope.current = $scope.current === i ? null : i;
            };
        },
        link: function(scope, el, attrs) {
          var itemSelector = '[item-selector]' || 'li',
              titleSelector = '[title-selector]' || 'h2',
              contentSelector = '[content-selector]' || 'div';
          $timeout(function(){
            var items = el[0].querySelectorAll(itemSelector);
            for (var i in items) {
              if (angular.isObject(items[i])) {
                var title = items[i].querySelectorAll(titleSelector)[0];
                var content = items[i].querySelectorAll(contentSelector)[0];
                scope.height.push({
                  'height': (content.offsetHeight + 10) + 'px'
                });
                angular.element(items[i]).addClass('item').attr({
                  'ng-class': '{\'open\':current == ' + i + '}'
                });
                angular.element(title).addClass('title').attr('ng-click', 'toggle(' + i + ')');
                angular.element(content).addClass('content').attr({
                  'ng-style': 'current == ' + i + '?height[' + i + ']:zero'
                });;

              }
            }
            $compile(angular.element(el).contents())(scope);
          });
        }
    }
})

Fiddle : http://jsfiddle.net/Lvc0u55v/10071/小提琴: http : //jsfiddle.net/Lvc0u55v/10071/

By default angular compiles all content of your directive, so then you call compile in link function, ng-click will be compiled twice.默认情况下,angular 会编译指令的所有内容,因此您在链接函数中调用 compile,ng-click 将被编译两次。

To prevent these behavior, protect your html from compiling by terminal and priority attrs, and compile it manually, excluding your directive by third argument(priority).为了防止这些行为,保护你的 html 不被终端和优先级 attrs 编译,并手动编译它,通过第三个参数(优先级)排除你的指令。

change directive definition to:将指令定义更改为:

{
....
terminal: true,
priority: 1000
...
}

and call compile like: $compile(el, null, 1000);并调用 compile 如下: $compile(el, null, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM