Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS custom model objects with methods?

When you have a JSON $resource how can you cast the resulting objects into more specific objects once obtained?

For example, right now they come back as an Array of Objects, but I want them to come back as an Array of "Appointment" objects, so that I can have some methods on that Appointment object which would answer questions about that Appointment object. Ex: Does This Appointment have any services associated with it? Is This appointment in the morning or afternoon?

At first I thought transformResponse hook would work from ngResource, but that doesn't appear to work. The return from that is not the actual objects. Seems that with that function you can only modify the actual data prior to the JSON parsing.

Finally, I question if this is even a proper angularJS technique? Or should these helper methods just show up in a controller or some other module and accept the object to work upon? I just think its cleaner to have them wrapped up in the object, but I admit that I'm not very experienced in angularJS.

like image 421
jr. Avatar asked Aug 18 '13 15:08

jr.


1 Answers

If you're using a factory and want to add a function you can for example add the function to the prototype of the returned item (DEMO):

app.factory('Appointment', ['$resource', function($resource) {
  var Item = $resource('appointments.json',{/*bindings*/},{/*actions*/});

  Item.prototype.hasServices = function() {
    if(this.services.length > 0) return true;
    else return false;
  };

  Item.prototype.partOfDay = function() {
    if(this.time.split(':')[0] > 12) return "afternoon";
    else return "morning";
  };

  return Item;

}]);

And then access it on your resource in the controller:

$scope.appointments = Appointment.query({}, function() {
    console.log($scope.appointments[0].partOfDay())
});

Or directly in the view inside for example an ng-repeat:

{{appointment.partOfDay()}}

To answer your last question, I think the above solution is a proper angularjs technique. As soon as you have functions associated with a specific resource type it's in my opinion the best to directly append them to the respective resource object. Why should you create helper functions in the controller when you have to pass the resource as a parameter and additionaly the functions may be used in multiple controllers or scopes?!

like image 80
Marcel Gwerder Avatar answered Oct 14 '22 06:10

Marcel Gwerder