如何防止重定向 <a href="#something>>在 Angular Js1.2 中 [英] How to prevent redirecting <a href="#something"> in Angular Js1.2

查看:16
本文介绍了如何防止重定向 <a href="#something>>在 Angular Js1.2 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中使用了 AngularJs-1.0.7 和 Bootstrap.最近我从 AngularJs-1.0.7 迁移到 AngularJs-1.2.我正在使用 Bootstrap 的 Accordions 和 Tabs.

I was using AngularJs-1.0.7 and Bootstrap in my application. Recently I migrated from AngularJs-1.0.7 to AngularJs-1.2. I am using Bootstrap's Accordions and Tabs.

Tab 的 HTML 代码包含 <a href="#id_for_content"> 如下所示.

Html code for Tab contains <a href="#id_for_content"> as shown below.

<ul id="myTab" class="nav nav-tabs">
    <li class="active"><a href="#firstTab" data-toggle="tab">Home</a></li>
    <li><a href="#secondTab" data-toggle="tab">Profile</a></li>
</ul>

<div id="myTabContent" class="tab-content">
    <div class="tab-pane fade in active" id="firstTab">
      <p>Content for first tab.</p>
    </div>
    <div class="tab-pane fade" id="secondTab">
      <p>Content For second tab.</p>
    </div>
</div>

在 Angular 的旧版本中,只有当我们提供像 <a href="#/firstTab"> 这样的锚标记时,才会发生路由更改.但是 AngularJs-1.2 重定向 <a href="#firstTab">.它不考虑 #firstTab 之间的 /.因此,在单击 Tab 时,它会重定向到 http://web_url/#/firstTab .如何解决这个问题?

In Angular's old versions, route change happens only if we give anchor tag like <a href="#/firstTab">. But AngularJs-1.2 redirects <a href="#firstTab">. It doesn't consider the / in between # and firstTab. Hence while clicking on Tab it redirects to http://web_url/#/firstTab . How to solve this issue?

我找到了解决此问题的方法.我为标签写了一个指令.在该指令中,我检查了 href 属性.如果匹配,则阻止其默认行为.检查以下代码.

I found a solution for this issue. I wrote a directive for a tag. In that directive I checked for href attribute. If it matches prevent from its default behavior. Check the following code.

app.directive('a', function() {
    return {
        restrict: 'E',
        link: function(scope, elem, attrs) {
            if(attrs.href === '#firstTab'|| attrs.href === '#secondTab'){
                elem.on('click', function(e){
                    e.preventDefault();
                });
            }
        }
   };
}); 

但是这种方法的问题是,我必须在这里检查每个选项卡 ID 或手风琴 ID.如果我为它们使用动态 ID,则无法签入指令.

But the problem with this method is, I have to check each and every tab ids or accordion ids here. If I use dynamic Ids for them, its not possible to check in directive.

如果您能找到更好的解决方案,请告诉我们.

If you can find better solution, let us all know about it.

推荐答案

只需将其添加到您的链接中:

Just add this to your links:

target="_self"

你准备好了;)

这篇关于如何防止重定向 &lt;a href=&quot;#something&gt;&gt;在 Angular Js1.2 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆