Tuesday, 10 September 2013

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

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/</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 }"></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!

No comments:

Post a Comment