AngularJS user model objects with methods?

When you have a JSON $ resource, how can you direct the resulting objects to more specific objects after receiving them?

For example, right now they are being returned as an array of objects, but I want them to be returned as an array of Destination objects, so that I could have some methods in this Destination object that would answer questions about this Destination object. Example: Does this purpose have any services related to it? Is this appointment in the morning or afternoon?

At first I thought that the hookResponse hook would work from ngResource, but that didn't work. The return from this is not a real object. It seems that with this function, you can only change the actual data until JSON is parsed.

Finally, I doubt that this is even the right angle technique? Or should these helper methods be displayed in the controller or some other module and accept an object to work on? I just think its cleaner to have them wrapped in an object, but I admit that I'm not very experienced in angularJS.

+8
angularjs ngresource
source share
1 answer

If you use a factory and want to add a function, you can, for example, add a function to the prototype of the returned element ( 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 run 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, ng-repeat:

 {{appointment.partOfDay()}} 

To answer your last question, I think the above solution is the proper angular method. Once you have functions associated with a particular type of resource, I find it best to add them to the corresponding resource object. Why should you create helper functions in the controller when you need to pass a resource as a parameter and, in addition, functions can be used in several controllers or areas ?!

+22
source share

All Articles