Search code examples
angularjsng-class

opening selected tab in list of menu using angularjs


I have a list this way. And in my home page i have three option candiatesignup, assessor signup and employer signup.now when i click from assessor want to make assessor selected. How to do it dynamically using angular js. I tried ng-class

 <li><a ng-class="{selected: activeTab == 'cd-candidate'}" href="#cd-candidate">Candidate Sign up</a></li>

this is without ng-class:

 <ul class="cd-switcher">
  <li><a class="selected" href="#cd-candidate">Candidate Sign up</a></li>
  <li><a href="#cd-assessor">Assessor Sign up</a></li>
 <li><a href="#cd-employer">Employer Sign up</a></li>
 </ul>

Solution

  • You can set the tab value in click and apply css class using ng-class conditional approach

    Try Below, You might not need the CSS.

    (function() {
      var app = angular.module('myApp', []);
    
      app.controller('TabCtrl', function() {
        this.tab = 1;
        //Set selected Tab
        this.setTab = function(tabId) {
          this.tab = tabId;
        };
        //Get Selected
        this.getTab = function(tabId) {
          return this.tab === tabId;
        };
      });
    })();
    .nav>li>a {
      position: relative;
      display: block;
      padding: 10px 15px;
    }
    
    .nav>li.selected>a {
      color: #fff;
      background-color: #428bca;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
    
    <div class="container">
      <section ng-app="myApp" ng-controller="TabCtrl as tab">
        <ul class="nav">
    
          <li ng-class="{selected:tab.getTab(1)}"><a href="#cd-candidate" ng-click="tab.setTab(1)">Candidate Sign up</a></li>
          <li ng-class="{selected:tab.getTab(2)}"><a href="#cd-assessor" ng-click="tab.setTab(2)">Assessor Sign up</a></li>
          <li ng-class="{selected:tab.getTab(3)}"><a href="#cd-candidate" ng-click="tab.setTab(3)">Employer Sign up</a></li>
        </ul>
      </section>
    </div>