【发布时间】:2016-04-15 08:16:47
【问题描述】:
我有一个问题,尽管元素具有 href 或 ng-href 属性,但似乎在元素上激活了角度 a directive。这会导致在呈现时对这些链接的任何点击与event.preventDefault() 产生角度。
我正在渲染的模板是在类似 ng-include 的指令中渲染的。依次在另一个指令中呈现。
ng-include 指令。
/*
* Use this when you need to include a view but want the scope to be transcluded.
*/
directiveModule.directive('rlInclude', [
'$compile',
'$templateRequest',
function (
$compile,
$templateRequest,
$sce
) {
'use strict';
return {
restrict: 'EA',
transclude: true,
link: function($scope, elem, attrs){
var templateUrl = attrs.src;
$scope.$watch(templateUrl, function(){
$templateRequest(arguments[0],false).then(function(html){
var template = angular.element(html);
elem.html(template);
$compile(elem.contents())($scope);
});
}, true);
}
}
}]);
在此指令中呈现以下模板时,锚点不可点击。
<div class="row">
<div class="col-xs-2">
<ul class="panel-header-links pull-right ">
<li ng-click="change()">
<a ng-href="{{'#/print/history/' + plan.id}}" class="nav-route cursor-pointer" target="history" >
<span class="glyphicon glyphicon-print"></span>
<span ng-bind="'PRINT' | translate"></span>
</a>
</li>
</ul>
</div>
</div>
所有变量都继承自转入作用域,并且模板被正确渲染,除了锚点之外,即使它们包含正确的信息。
我想要的是一种避免这种情况的方法。我可以使用$route 提供程序通过单击锚点来解决此问题,但由于该组件应该被其他人使用,我更愿意一劳永逸地解决这个问题。
我的 Angular 版本是 1.5.4 我的 JQuery 版本是 2.2.3
更新
似乎错误与此代码有关,有些错误如何将 onClick 处理程序两次附加到锚点。
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (!attr.href && !attr.xlinkHref) {
return function(scope, element) {
// If the linked element is not an anchor tag anymore, do nothing
if (element[0].nodeName.toLowerCase() !== 'a') return;
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
element.on('click', function(event) {
// if we have no href url, then don't navigate anywhere.
if (!element.attr(href)) {
event.preventDefault();
}
});
};
}
}
});
单击链接时,单击处理程序会触发两次。第一次 element.attr(href) 是真的,第二次不是。这会阻止窗口的启动。
如果我通过输入 href 第二次通过检查,我会正确重定向。
【问题讨论】:
标签: javascript html angularjs