3

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!

2 Answers 2

4

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 "";
}
Sign up to request clarification or add additional context in comments.

1 Comment

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'.
3
<a href="#/phones/{{phone.id}}" ng-class="{'matching': phone.name==query }">{{phone.name}}</a>

that should do it for exact matches.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.