Search code examples
angularjsurlcontrollerng-classroute-provider

data-ng-class conditions is not working when changing url manually


I did a conditional statement on the div on data-ng-class and I want to somehow add this scope to the controller and specify when the url is /vegetarian to apply class 'egg' and i manually change url i want the class 'bacon' to be applied, but its not working, where I have i gone wrong?

html:

<div data-ng-class="{'egg': isVeggie, 'bacon': !isVeggie }">
  Text here
</div>

controller:

app.controller('foodCtrl', function ($scope, $location) {

  $scope.location = $location;
  $scope.isVeggie = false;


  $scope.isVeggie = function() {
    if(isVeggie === $location.path('/vegetarian')) {
      return true;
    }
  }

});

this is not working. When I type /vegetarian, the class egg is being applied, but when I change the url to something else like /breakfast, the class 'egg' remains. How can I make this work? Thanks


Solution

  • Why the property and the function with the same name ? After all you will have only the function

    $scope.isVeggie = false;
    
    $scope.isVeggie = function() {
        if(isVeggie === $location.path('/vegetarian')) {
           return true;
        }
    }
    

    Change your code to have only the function.

    Only

    $scope.isVeggie = function() {
            if(isVeggie === $location.path('/vegetarian')) {
               return true;
            }
        }
    

    and markup

    <div data-ng-class="{'egg': isVeggie(), 'bacon': !isVeggie() }">
      Text here
    </div>