Search code examples
angularjsangular-ui-bootstrapbootstrap-4angular1.6

Bootstrap 4 tabs break in AngularJS


I found when using bootstrap tab with pills, the:

<a class="nav-link" id="tabItem" data-toggle="pill" href="#tabItem"> example </a> 

breaks the angular application causing it to navigate back to the page loading the first tab and selecting the first default pill.

I tried adding:

_target="self"

...adding this fixes navigation only for the first four clicks, and then it breaks again. When I inspect the page I see that the 'active' class never gets cleared with this is set.

I also tried adding:

"dependencies": {
     "angular1-ui-bootstrap4": "2.4.22"
 }

via npm, but the amount of work needed to create a layout and modify some of the pre-designed behavior wasn't worth my time.

It was a long path to find a minimal-code, tight solution, but I am posting this question to help others.


Solution

  • I fixed this behavior by adding a custom directive in angular that removes the old active class and shows the tab clicked on:

    //
    // when bootstrap adds the # to pills it ruins everything!!
    // fix that with this:
    //
    app.directive('tabFix', function () {
        return function (scope, element, attrs) {
            $(element).click(function (event) {
            $(this).siblings("a").removeClass('active');           
            event.preventDefault();
            $(this).tab('show');         
            });        
        }
    });
    

    then to call the directive, add tab-fix onto the anchor element:

    <a class="nav-link" id="tabItem" data-toggle="pill" href="#tabItem" tab-fix> example </a> 
    

    It fixes everything!