Transforming API Data Objects in AngularJS

The Problem

AngularJS is awesome, but one thing sorely lacking from it is the ability to use information from HTTP endpoints as Business Logic objects. For example, if you get a list of files from an API endpoint, all you get are the attributes from that endpoint, no methods.

[{"filename": "avi_1003.mov", "filesize": 1033293},
{"filename": "avi_1123.mov", "filesize": 10299932},
{"filename": "avi_1456.mov", "filesize": 7702345}]

Wouldn’t it be nice to be able to call methods on those data objects, like a method to get a human readable filesize?

The Solution…

… Is actually really simple: define a class with methods and then tell Angular to transform that data after the promise is resolved. When you use AngularJS to iterate over each value in the returned information, you can tell it to extend that information with the methods you just defined in your ViewModel. See below for an example.

// define a Movie class somewhere in JS
function Movie(){}

Movie.getFilesizeInMB()
{
  return this.filesize / 1024 / 1024 + " Mb";
}

...
// in your service or controller, transform the data into objects of type Movie
$http.get("api/movies").success(function(data){
    $scope.movies = angular.forEach(data.movies, function(value){
        angular.extend(value, Movie);
    });
});

Now you have a super simple way to add methods to the data from your API! Go Angular!

facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Thanks for your thoughts!