0

I'm pretty much a newbie in the AngularJS world. This is my problem. I would like to update the selected tab based on the url, so that the selected tab changes when the url changes.

This is my js:

app.config(function($routeProvider, $locationProvider){
      $routeProvider
        .when('/page1', {
          templateUrl: '/views/pages/page1.html',
          controller: "TabController",
          tab: 1
        })
         .when('/page2', {
          templateUrl: '/views/pages/page2.html',
          controller: "TabController",
          tab: 2
        })
        .otherwise({
          template: "Error 404"
        });

        $locationProvider.html5Mode({enabled: true, requireBase: false});
    });

    //Tabs
    app.controller("TabController", function($scope, $route){
      $scope.activeTab = 0;

      if(typeof $route.current != "undefined"){
        setTimeout(function(){$scope.activeTab = $route.current.activeTab; console.log($scope.activeTab);},100);
      }
    });

And this is my html:

<div ng-controller="TabController">
  <!-- Tabs -->
  <section class="section section--xs">
    <div class="container">
      <div class="tab">
        <div class="tab__single" ng-class="{active: activeTab === 1}">
          <a href="/page1" class="tab__single__name">Page 1</a>
        </div>
        <div class="tab__single" ng-class="{active: activeTab === 2}">
          <a href="/page2" class="tab__single__name">Page 2</a>
        </div>
      </div>
    </div>
  </section>
  <!-- ./tabs -->

  <!-- Content -->
  <ng-view></ng-view>
  <!-- ./content -->
</div>

I try and if I log the tab value, it actually updates, because it logs the correct value, but then the new tab doesn't get selected. Any suggestions?

2
  • this may help Commented Jan 7, 2017 at 18:09
  • @ricky I tried the very first solution, but it doesn't update anyway! Commented Jan 7, 2017 at 18:29

1 Answer 1

0

You could create a function to search in your url parameters:

$scope.isActive = function (viewLocation) { 
    return viewLocation === $location.path();
};

HTML:

<div class="tab">
        <div class="tab__single" ng-class="{active: isActive('page1')}">
          <a href="/page1" class="tab__single__name">Page 1</a>
        </div>
        <div class="tab__single" ng-class="{active: isActive('page2')}">
          <a href="/page2" class="tab__single__name">Page 2</a>
        </div>
      </div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! This seems to work pretty well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.