Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs best way to dynamically change CSS class based on input query

In the AngularJS phonecat tutorial, there is an input box which is used to apply a filter to ng-repeat. This works great for returning a subset array to display on the screen.

Here is what the code looks like:

Search: <input ng-model="query">
  <ul class="phones">

...

    <li ng-repeat="phone in phones | filter:query | orderBy:orderProp" class="thumbnail">
      <a href="#/phones/{{phone.id}}" class="thumb"><img ng-src="{{phone.imageUrl}}"></a>
      <a href="#/phones/{{phone.id}}">{{phone.name}}</a>
      <p>{{phone.snippet}}</p>
    </li>
  </ul>

I was wondering what's the best way to dynamically add a CSS class to matching elements. An example use case of this would be to add a background-color (style .matching{}) to all matching elements.

Comparing the query text in ng-class did NOT work:

        <li ng-repeat="phone in phones" class="thumbnail">
      <a href="#/phones/{{phone.id}}" class="thumb"><img ng-src="{{phone.imageUrl}}"></a>
      <a href="#/phones/{{phone.id}}" ng-class="{'matching': phone.name.indexOf(query) != -1 }">{{phone.name}}</a>
      <p>{{phone.snippet}}</p>
    </li>
  </ul>

I am new to angular and trying to just get a feel for the framework. Do I have to bind the query text to the element somehow so that the comparison works? Would a better approach be to handle this through a custom directive?

Any help is appreciated - thanks!

like image 373
Chris Ridmann Avatar asked Nov 17 '25 16:11

Chris Ridmann


2 Answers

Try setting the class to a function in the controller. ng-class="GetMatchingClass(phone)"

$scope.GetMatchingClass= function(phone){
    if(phone.name.indexOf(query) != -1 ){return "matching"}
    return "";
}
like image 163
sasonic Avatar answered Nov 20 '25 07:11

sasonic


<a href="#/phones/{{phone.id}}" ng-class="{'matching': phone.name==query }">{{phone.name}}</a>

that should do it for exact matches.

like image 43
Anton Avatar answered Nov 20 '25 07:11

Anton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!