我在模板中使用accordion指令,而在手风琴里面,我在元素上添加了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);
});
}
}
})
答案 0 :(得分:1)
默认情况下,angular会编译指令的所有内容,因此在链接函数中调用compile,ng-click将被编译两次。
要防止出现这些行为,请保护您的html不受终端和优先级attrs的编译,并手动编译,不包括第三个参数(优先级)的指令。
将指令定义更改为:
{
....
terminal: true,
priority: 1000
...
}
并调用编译:{{1}}