gpt4 book ai didi

javascript - 在 Angular Directive(指令)内编译模板后,超链接不起作用

转载 作者:行者123 更新时间:2023-11-27 23:05:27 24 4
gpt4 key购买 nike

我有一个问题,它看起来有 Angular a directive尽管元素具有 href 或 ng-href 属性,但仍会在元素上激活。这会导致渲染时对 event.preventDefault() 任何对这些链接的点击产生 Angular 。

我正在渲染的模板是在类似 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);
}
}
}]);

在此指令内渲染以下模板时, anchor 不可单击。

<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>

所有变量都从嵌入范围继承,并且除了不可点击的 anchor 之外,模板都会正确呈现,即使它们包含正确的信息。

我想要的是一种避免这种情况的方法。我可以使用 $route 提供程序通过单击 anchor 来解决此问题,但由于该组件应该由其他人使用,我更愿意以正确的方式一劳永逸地解决此问题.

我的 Angular 版本是 1.5.4我的JQuery版本是2.2.3

更新

似乎错误与此代码有关,以及如何将 onClick 处理程序两次附加到 anchor 。

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) 为 true,第二次则不是。这会阻止窗口的启动。

如果我第二次通过输入 href 来通过检查,我会被正确重定向。

最佳答案

这个问题我已经解决了。问题在于,在编译的层次结构的较高位置有一个父 anchor ,我的指令被插入其中。这部分代码没有受到我的更改的影响,因此很难调试。可以这样表示的结构。

<a id="parentWithoutHref">
<directive>
<...>
<a id="theBrokenLink" href="url" />
</...>
</directive>
</a>

发生的情况是,事件在通过第一个 Angular anchor 指令检查后正确冒泡,并在第二个没有 href 属性的标签处停止。通过用 span 或 div 替换原本不应该是 anchor 的 anchor 可以轻松解决此问题。

关于javascript - 在 Angular Directive(指令)内编译模板后,超链接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36641795/

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