RonE
RonE

Reputation: 434

Changing ng-class based on conditional statement in controller

I am trying to update ng-class with a CSS class that has a specific background image. For example:

<button id="search" ng-class="{travel: travel }">Search</button>

for(var i = 0; i < arrayLength; i++) {

    var descriptions = uniqueFilters[i].split(' ');

       if(descriptions.indexOf('Travel') > -1) {
           $scope.travel = "travel";

             } else {

                }
           }}

I receive an array of strings. I take the strings, split the sentences into individual words, and then if they have a specific word, update the class to apply a specific background image.

How do I get this to work?

Upvotes: 0

Views: 41

Answers (2)

cnorthfield
cnorthfield

Reputation: 3501

You can pass a function into the ngClass directive which needs to evaluate to either true or false.

If you create a function travel in your controller then pass it into the directive in your view:

<button id="search" ng-class="{travel: travel() }">Search</button>

In your controller:

// ... your other code

$scope.travel = function() {

  for (var i = 0; i < arrayLength; i++) {

    var descriptions = uniqueFilters[i].split(' ');

    if (descriptions.indexOf('Travel') > -1) {

      // we have satisfied our condition
      // the class 'travel' will be added to the button
      return true;

    }

  }

  // we didn't satisfy the condition in our loop
  // the class 'travel' will NOT be added to the button
  return false;

}

Upvotes: 0

Gustavo Gabriel
Gustavo Gabriel

Reputation: 1296

As @Dave V said in his comment the ng-class directive requires a boolean value, so travel needs to be true:

$scope.travel = true;

Or if you need it to be a string, you can do something like:

ng-class="{travel: travel == 'travel' }"

Hope it helps =)

Upvotes: 1

Related Questions