gpt4 book ai didi

javascript - Angular Directive(指令)编译器触发 ng-click 两次

转载 作者:太空宇宙 更新时间:2023-11-04 16:32:12 25 4
gpt4 key购买 nike

我在我的模板中使用了 Accordion 指令,并且在 Accordion 内部我在元素上添加了 attr ng-click 。当我单击该元素时,它会触发两次。

fiddle :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);
});
}
}
})

fiddle :http://jsfiddle.net/Lvc0u55v/10071/

最佳答案

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

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

将指令定义更改为:

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

并调用编译,如下所示:$compile(el, null, 1000);

关于javascript - Angular Directive(指令)编译器触发 ng-click 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39702094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com