gpt4 book ai didi

javascript - 如何克隆 ui-sref

转载 作者:行者123 更新时间:2023-12-03 06:02:06 26 4
gpt4 key购买 nike

我正在寻找编写一个指令,允许单击外部元素来克隆其所包含元素之一的 ui-sref ,这样单击外部元素的行为与单击.cloned 元素

<div clone-click=".cloned">
...
<a class="cloned" ui-sref="root.a" ng-if="true">example</a>
<a class="cloned" ui-sref="root.b" ng-if="false">example</a>
...
<a ui-sref="root.c">elsewhere</a>
...
</div>

我尝试了触发点击的属性指令

app.directive('cloneClick', function() {
return {
restrict: 'A',
scope: {
selector: '@cloneClick'
},
link: function(scope, element) {
element.click(function() {
element.find(scope.selector).not(':disabled').first().click();
})
}
};
})

但这会导致无限循环或其他问题并且不起作用。我怎样才能让它发挥作用?或者有更好的方法来实现这一目标吗?

最佳答案

您没有考虑事件冒泡。就像现在一样,子级上的任何点击事件都已经冒泡到父级,此时您告诉它再次单击同一元素......因此,如果您想要的目标被单击,则无限循环

我的建议是防止该事件在 <a> 上传播。

如果<a>单击其本身,让浏览器处理重定向,如果单击父级的任何其他部分,则使用 $location使用 ui-sref 的 href 值进行重定向的服务生成。

类似于:

link: function(scope, element) {
var $link = element.find(scope.selector).not(':disabled').first();
// prevent bubbling on target link
$link.click(function(e) {
e.stopImmediatePropagation()
});

element.click(function(e) {
// make sure target link wasn't element clicked
if (e.target !== $link[0]) { // assumes no child tags in `<a>`
$location.url($link.attr('href'));
}
});
}

您可能需要根据是否使用 html5mode 进行一些调整

编辑:写完这篇文章后,我想到您也许可以触发 <a> 上的点击而不是使用$location因为事件传播(冒泡)仍然被阻止

关于javascript - 如何克隆 ui-sref,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39712445/

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