3

enter image description hereI have 3 routes containing 3 forms Im trying to set bootstrap active class on current tab based on the current route in angular.I used angular route module. How can I achieve this. I m attaching the js code please check and help please

            angular.module('bankAppOnline',     ['ngSanitize','ngRoute','ngAnimate','ngQuantum'])
                .config(['$routeProvider',
                    function($routeProvider) {
                        $routeProvider.
                        when('/firststep', {
                            templateUrl: 'templates/firstformtemplate.html',
                            controller: 'firstformCtrl',
                            containerClass: 'active'

                        }).
                        when('/secondstep', {
                            templateUrl: 'templates/secondformtemplate.html',
                            controller: 'secondformCtrl',
                            containerClass: 'active'


                        }).
                        when('/thirdstep', {
                            templateUrl: 'templates/thirdformtemplate.html',
                            controller: 'thirdformCtrl',
                            containerClass: 'active'

                        }).
                        otherwise({
                            redirectTo: '/firststep'
                        });
                    }])
               .run(function($rootScope){

                $rootScope.$on('$stateChangeSuccess',function(event, toState, toParams, fromState, fromParams){
                    console.log(event);
                    console.log(toState);
                    console.log(fromState);
                    console.log(toParams);
                    $rootScope.containerClass = toState.containerClass;
                });

            })
                .controller('Main-Ctrl',function($scope)
            {
                $scope.containerClass =  "active";
            })
                .controller('firstformCtrl', function ($scope, Customer) {

                   $scope.cities = ['Hyderabad','Vizag','Vijayawada','Bangalore','Delhi','Mumbai','Chennai','Noida','Pune','Tirupathi'];
                   $scope.professions = ['Doctor','Teacher','Engineer','Lawyer'];
                   $scope.customer = Customer.get();
                 $scope.reset = function() {


                    $scope.firstform.$setPristine();
                       var restore = {
                        "firstname": "",
                        "lastname": "",
                        "age": "",
                        "city": "",
                        "profession": "",
                        "mobile": ""
                    };
                    angular.extend($scope.customer, restore);

                }  
              })
              .controller('secondformCtrl', function ($scope, Customer) {
                  $scope.designations = ['ChairmanVice Chairman',
            'Chairman cum Managing Director',
            'Managing Director',
            'Sr. Vice president',
            'Vice President',
            'General Manager',
            'Joint General Manager',
            'Deputy General Manager',
            'Asst. General Manager',
            'Chief Manager',
            'Sr. Manager',
            'Manager',
            'Joint Manager',
            'Deputy Manager',
            'Asst. Manager',
            'Sr. Officer',
            'Officer',
            'Jr. Officer',
            'Sr. Associate',
            'Associate',
            'Jr. Associate',
            'Assistant' ];
                $scope.customer = Customer.get();
                 $scope.reset = function() {

                    $scope.secondform.$setPristine();
                         var restore = {
                        "pan":"",
                         "income":"",   
                         "company":"",
                         "designation":"",
                         "address":"",
                         "pin":""
                    };
                    angular.extend($scope.customer, restore);

                }  
              })
                .controller('thirdformCtrl', function ($scope,$http,Customer,$alert) {

                $scope.accounts = ['Savings','Basic checking','Interest-bearing','Market-Deposits','Certificates of deposit'];
                $scope.customer = Customer.get();
                  $scope.reset = function() {
                    $scope.thirdform.$setPristine();
                       var restore = {
                       "accountType":"" ,
                 "fdCheck":false,
                 "creditcardCheck":false
                    };
                    angular.extend($scope.customer, restore);

                };
                    $scope.sendPost = function() {
                       var data =  $scope.customer;
                        console.log($scope.customer);
                        $http.post("/users", data).success(function(data, status) {
                            $scope.status = status;

                                $alert('form saved successfully.','Oley!', 'success', 'top-right');

                            console.log($scope.status);
                        })
                            .error(function(response, status){
                                //$alert(options)
                                //for using more option create object
                                $alert({title:'Error', content:'An error occured',placement:'top-right',alertType:'danger'});
                            })
                    };

                })
              .factory('Customer', function () {
                var customer = {
                    "firstname": "",
                    "lastname": "",
                    "age": "",
                    "city": "",
                    "profession": "",
                    "mobile": "",
                    "accountType": "",
                    "fdCheck": false,
                    "creditcardCheck": false,
                    "pan": "",
                    "income": "",
                    "company": "",
                    "designation": "",
                    "address": "",
                    "pin": ""
                };

                return {
                  get: function () {
                    return customer;
                  }
                }
              });
kiran gudla
  • 177
  • 1
  • 11

4 Answers4

7

This can be achieved using ng-class. Just make use of $location in your controller. This example is quite simple. Here we add an active class to div when $location.path() equals '/'.

Then we setup a conditional ng-class in our view that adds the active class.

View

<div ng-class="{active: location === '/'}">
  <p>The parent DIV will have active class added when location path equals '/'</p>
</div>

Controller

.controller('MainCtrl', function ($scope, $rootScope, $location) {
    $scope.location = $location.path();
    $rootScope.$on('$routeChangeSuccess', function() {
        $scope.location = $location.path();
    });
});
perry
  • 520
  • 4
  • 12
  • its working only when u type the url and a reload happens not happening when we use tabs or next achor tag links.please suggest?? – kiran gudla Jan 18 '16 at 15:49
  • Watch for the $routeChangeSuccess event and update the location variable. Should be fairly straight forward. Updated the sample code. The initial location is only loaded on controller load. Now depending on your own application this logic should maybe not be in a single controller. Depends on your app really. – perry Jan 19 '16 at 02:20
  • thanks man, I implemented in the same way i used locationchangeSuccess event – kiran gudla Jan 20 '16 at 04:15
1

Since you tagged your question with angular-ui-router I assume you are using it.

Using UI routers ui-sref combined with ui-sref-active will let you assign a class for the currently active state (or any child states).

Here for example. If state is app.tab1 (or a child state) the active class will be applied to the li element.

<ul>
  <li ui-sref-active='active'>
    <a ui-sref="app.tab1">link</a>
  </li>
  <li ui-sref-active='active'>
    <a ui-sref="app.tab2">link</a>
  </li>
  <li ui-sref-active='active'>
    <a ui-sref="app.tab3">link</a>
  </li>
</ul>

See http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref-active

perry
  • 520
  • 4
  • 12
  • please check the code I have added , I m not using ui-router i m using angular route module – kiran gudla Jan 16 '16 at 13:36
  • Ok. You had tagged it with UI router and like I said that was an assumption. Then using a conditional ng-class in combination with $location will probably be the way to go. See new answer. – perry Jan 17 '16 at 23:55
0

You can use ng-class

Please read the documentation

Muhammad Azeem
  • 1,129
  • 1
  • 12
  • 16
0

This is for the total beginner like me:

HTML:

<script src="~/Content/src/angularjs/angular.min.js"></script>
<script src="~/Content/src/angularjs/angular-route.min.js"></script>

<ul>
  <li>
      <a ui-sref="Basics" href="#Basics" title="Basics" class="nav-link--link">Basics</a>
  </li>
</ul>

<div ng-app="myApp" ng-controller="MainCtrl">
  <div ng-view>

  </div>
</div>

Angular:

//Create App
var app = angular.module("myApp", ["ngRoute"]);    

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Coming soon</p>"
      })
      .when("/Basics", {
        templateUrl: "/content/views/Basic.html"
      });      
});    

//Controller 
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
    $scope.location = $location.path();
    $rootScope.$on('$routeChangeSuccess', function () {
      navChanged();
    });
  });

  function navChanged() {
    setTimeout(function () {
      var links = angular.element(document.getElementsByClassName("nav-link--link"));
      var activeLink = null;
      for (var i = 0; i < links.length; i++) {
        var link = links[i]
        var linkElement = angular.element(link);
        linkElement.removeClass("active");
        var hash = location.hash.replace("#/", "#")
        if (link.hash && hash.split("#")[1] == link.hash.split("#")[1]) {
          activeLink = linkElement;
        }
      }
      activeLink.addClass("active");
    }, 100);
  };
Darrel K.
  • 1,611
  • 18
  • 28