0

I have just started using angular js. I am using it with CodeIgniter. I am trying to add a {class="active"} if a condition matches.

I am trying to add a active class to a <li> if its title matches with the last segment of url.

i.e.

 if(title of this nav_menu matches with the last uri segment)
    add "active" class
 else
    do nothing

My code is as follows :

header.php

<ul class="nav navbar-nav" ng-app="" ng-controller="menuController">
    <li ng-repeat="x in menus" ng-class="{'active': x.name = scope}">
        <a ng-href="http://{{ x.link}}">{{ x.name }}</a>
    </li>
</ul>

footer.php

<script
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>


<script>
    function menuController($scope) {

        $scope.menus = [ {
            name : "Home",
            link : "projects/test/home"
        }, {
            name : "Daily Special",
            link : "projects/caesar/daily-especial"
        }, {
            name : "Menu",
            link : "projects/test/menu"
        }, {
            name : "Special",
            link : "projects/test/special"
        }, {
            name : "Gallery",
            link : "projects/test/gallery"
        }, {
            name : "About us",
            link : "projects/test/about-us"
        }, {
            name : "Contact",
            link : "projects/test/contact"
        } ];

        $scope.current = '<?php echo $this->uri->segment(2); ?>';

    }
</script>

I think the problematic step is $scope.current = 'uri->segment(2); ?>';

1
  • 1
    Do you mean something like: ng-class="{'active': x.name.toLowerCase().replace(/ /g, '-') == x.link.substr(link.lastIndexOf('/') + 1, link.length)}"? Commented Nov 12, 2014 at 6:19

1 Answer 1

5

Here is how ng-class works, say for the below example

ng-class="{ 'active': menu.IsCurrentTab, 'inactive': !menu.IsCurrentTab }"

class active will be added if the scope variable menu has IsCurrentTab value true. Else class inactive will be used.

In your case firstly I do not know what this code of your's does

$scope.current = '<?php echo $this->uri->segment(2); ?>';

If this is putting the current menu name in the $scope.current variable, then all you need to do is

<li ng-repeat="x in menus" ng-class="{'active': x.name == current}" >

Hope this helps.

Edit:

Would want you to check if the value is filled in your $scope.current variable.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Yasser. Could you simplify that a bit?
Silly of me, I used x.name = scope, when it had to be x.name == scope :D.

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.