0

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?

1
  • Whatever you are using as the conditional in the ng-class, it needs to be a boolean value, not a string. Maybe do something like: if(descriptions.indexOf('Travel') > -1) { $scope.travel = true; } else { } } Commented Sep 6, 2016 at 20:44

2 Answers 2

1

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 =)

Sign up to request clarification or add additional context in comments.

Comments

0

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;

}

4 Comments

You could simplify that further with just a return descriptions.indexOf('Travel') > -1
@DaveV No you can't, it would return within the first iteration of the loop every time
ahhh, I didn't catch that the false was outside the loop, my bad
@DaveV Good thinking about it though!! :) - I've edited the code comments to make it a bit more clear

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.