Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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 "";
}
share|improve this answer
    
This ended up working - thanks! I guess ng-Class has two-way data binding as well, so I wouldn't have to link each <li> to ng-Model='query'. –  Chris Ridmann Sep 13 '13 at 13:48
<a href="#/phones/{{phone.id}}" ng-class="{'matching': phone.name==query }">{{phone.name}}</a>

that should do it for exact matches.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.