Search code examples
angularjscontrollerangularjs-routing

change css class depending on location path via controller


Can someone help me on how I can switch the css class of an element based on the url path in the controller?

I tried to attempt this with code below, when I change the path to 'user' the class does not change, please help, thanks.

the html:

<figure data-ng-class="{'account-balance': !isVisitor, 'lang-selector': isVisitor}">

in the controller:

$scope.accountView = function(viewLocation) {
if(viewLocation === $location.path('/visitor')) {
  return $scope.isVisitor;
}

};


Solution

  • Here's my answer. The only thing is I don't know what viewLocation is.

    I would write it like this:

    <figure data-ng-class="accountView(viewLocation)">

    The function would be:

    $scope.accountView = function(viewLocation) {
      var res;
      if(viewLocation === $location.path('/visitor')) {
        res = 'lang-selector';
      } else {
        res = 'account-balance';
      }
      return res;
    };
    

    This keeps all logic in the controller and gives you more control. You could also make this a switch statement rather than an if/else. Make sure $location is injected in the controller.