AngularJS: Filter your data

Sometimes, you need to filter your data in order to get to one or more specific records in your JSON-object. You probably know about the possibility of adding | filter: {expression} to your ng-repeat lists, just like so:

  <xsl:attribute name="ng-repeat">
    <xsl:text>orderlinedescription in line.OrderLineDescriptions | filter:'</xsl:text><xsl:value-of select="sc:language()"></xsl:value-of><xsl:text>'</xsl:text>

However, I didn’t know that it is also possible to filter data in the controller – before sending data to the view. If you want to use this method, you have to inject $filter into your controller.

Just like the following example here where I search for a particular photo by looking up the ID:

function EditPhotoCtrl($scope, $location, $routeParams, globals, messageService, $filter) {
  var image = [];

  $scope.getServiceOrderByOrderNumber($scope, globals, $routeParams.ordernumber, function(status, result) {
    $scope.serviceorder = result;

    // Get the correct photo
    image = ($filter('filter')(result.Photos, {Id: $routeParams.Id}));
    $scope.image = image[0];

What happens is that $filter generates a new array consisting of the found results. In the example I just need one record, so I select the first one. But you could also generate a new list consisting of the found results.

That’s it. AngularJS continues to amaze me. 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s