Greg
Greg

Reputation: 1710

Set variable while navigating using angular

Im trying to create a navigation bar but i get stuck with this code.

What happens is when i click the menu it navigates to the right page. When i click again the variable is set. But is it possible to set the variable while navigating.

<div>

    <nav class="{{active}}" >

        <!-- When a link in the menu is clicked, we set the active variable -->

        <a href="#/" class="home" ng-click="active='home'">Home</a>
        <a href="#/second" class="projects" ng-click="active='1234'">Projects</a>
        <a href="#/third" class="services" ng-click="active='services'">Services</a>
    </nav>

    <p ng-hide="active">Please click a menu item</p>
    <p ng-show="active">You chose <b>{{active}}</b></p>

</div>

EDIT

I change the header page to this but i still can get it working.

<div>

    <nav ng-controller="testController" class="{{active}}">

        <!-- When a link in the menu is clicked, we set the active variable -->

        <a href="#/" class="home" >Home</a>
        <a href="#/second" class="second" >second</a>
        <a href="#/third" class="third" >third</a>

    </nav>


</div>

css

nav.home .home,
nav.second .second,
nav.third .third{
    background-color:#e35885;
}

Upvotes: 0

Views: 158

Answers (1)

Black0ut
Black0ut

Reputation: 1737

You can achieve that by listening to location changes and using the ng-class directive :

CSS :

.active, .active:focus{
    color: red;
}

HTML :

  <div ng-app="testApp">
        <div ng-controller="testController">
            <div>
                <!-- When a link in the menu is clicked, we set the active variable -->
                <a href="#/" ng-class="isPageSelected('Home')">Home</a>
                <a href="#/second" ng-class="isPageSelected('Second')">second</a>
                <a href="#/third" ng-class="isPageSelected('Third')">third</a>
            </div>
        </div>
</div>

Javascript :

var app = angular.module('testApp', []);
app.controller('testController', function ($scope, $location, $rootScope, $log) {
    $scope.locationsDescriptions = {
        '#/': 'Home',
        '#/second': 'Second',
        '#/third': 'Third'
    }
    $scope.isPageSelected = function (pageName) {
        return $scope.active == pageName ? 'active' : '';
    }
    $scope.$on("$locationChangeSuccess", function (event, next, current) {
        var location = this.location.hash.toLowerCase();
        $scope.active = $scope.locationsDescriptions[location];
    });
});

Upvotes: 2

Related Questions