1

我在我的模板中使用手风琴指令,在手风琴内部我正在添加attr ng-click一个元素。当我单击该元素时,它会触发两次。

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

代码 :

//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);
          });
        }
    }
})

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

4

1 回答 1

1

默认情况下 Angular 编译你的指令的所有内容,所以你在链接函数中调用 compile,ng-click 将被编译两次。

为了防止这些行为,请保护您的 html 不被终端和优先级属性编译,并手动编译它,通过第三个参数(优先级)排除您的指令。

将指令定义更改为:

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

并像这样调用编译:$compile(el, null, 1000);

于 2016-09-26T12:57:02.640 回答