Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent redirecting <a href="#something"> in Angular Js1.2

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.

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>

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?


My Solution

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();
                });
            }
        }
   };
}); 

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.

like image 987
Sajith Avatar asked Sep 11 '25 03:09

Sajith


1 Answers

Just add this to your links:

target="_self"

And you're ready ;)

like image 158
Vassilis Pits Avatar answered Sep 13 '25 22:09

Vassilis Pits