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

Community
  • 1
  • 1
Danger14
  • 760
  • 2
  • 12
  • 33
  • 3
    `ng-class="{ active: isActive('/') || isActive('/main/')}"` ? and did you check if `$location.path()` is what you expect? – PSL Aug 19 '14 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 } – fiskers7 Aug 19 '14 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. – Surreal Dreams Aug 19 '14 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. – Gruff Bunny Aug 19 '14 at 19:57
  • @fiskers7 Yes, my original code only worked for the second URL path. – Danger14 Aug 19 '14 at 20:12
  • @PSL Yes, `console.log($location.path());` returns the correct path. You and fiskers7 both have the best answer. Who wants the credit? :) – Danger14 Aug 19 '14 at 20:17
  • let isActive take multiple arguments `isActive('/', '/main/')` and inside isActive do `return [].indexOf.call(arguments, location.path()) > -1` – PSL Aug 19 '14 at 20:21

2 Answers2

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

PSL
  • 123,204
  • 21
  • 253
  • 243
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 }"

fiskers7
  • 918
  • 8
  • 8