Search code examples
angularjsng-class

Adding multiple expressions using ng-class in AngularJS


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


Solution

  • 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