1

I am trying to set the class .active when the path is http://localhost/#/ or http://localhost/#/main/ as both paths are the same page.

Why does ng-class="{'class1' : expression1, 'class1' : expression2}" not work?

Controller

angular.module('testApp')
  .controller('NavmenuCtrl', function ($scope, $location) {
  $scope.isActive = function (providedPath) {
    return providedPath === $location.path();
  };
});

Partials View

<li ng-class="{ active: isActive('/'), active: isActive('/main/')}">
  <a href="#/">Home</a>
</li>

Related links

Adding multiple class using ng-class

AngularJS ng-class multiple conditions

Oliver Tupman: Keep CSS classes out of your Angular controllers

Scotch.io: the many ways to use ng-class

7
  • 3
    ng-class="{ active: isActive('/') || isActive('/main/')}" ? and did you check if $location.path() is what you expect? Commented Aug 19, 2014 at 19:48
  • 1
    Does it work for one path and not the other? You could also write it using the or operator for one instance of the class. { active: condition1 || condition2 } Commented Aug 19, 2014 at 19:49
  • 1
    Try inserting a console.log("provided: " + providedPath + " location: " + $location.path()); into your isActive method. You can then see in the console what is being compared to what, which can often point out problems. Commented Aug 19, 2014 at 19:51
  • 1
    It doesn't work because angular evaluates the argument as an object and in your example the property class1 is duplicated. Commented Aug 19, 2014 at 19:57
  • @fiskers7 Yes, my original code only worked for the second URL path. Commented Aug 19, 2014 at 20:12

2 Answers 2

3

Making my comment an answer, Yes your issue is with the duplicate keys, you could just do:-

ng-class="{ active: isActive('/') || isActive('/main/')}"

Or probably better:-

Let your isActive class accept multiple arguments:-

$scope.isActive = function () {
    //Look for a match in the arguments array
    return [].indexOf.call(arguments, location.path()) > -1;
};

and use it as:-

ng-class="{ active: isActive('/', '/main/')}"

Shim support for indexOf for older browsers

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

2 Comments

Have an upvote for getting your answer in before me!
@fiskers7 Can you put your comment as an answer so I can at least up vote it?
1

Day late but hopefully worth something.

You could also write it using the or operator for one instance of the class.

ng-class="{ 'active': condition1 || condition2 }"

Comments

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.