javascript - Count number of elements in $resource.query() object -
i'm trying count number of elements returned $resouce.query()
object, can increment , use id next object saved.
following service communicate server:
eventsapp.factory('eventdata', function($resource) { var resource = $resource('/data/event/:id', {id: '@id'}); return { getevent: function(eventid) { return resource.get({id: eventid}); }, saveevent: function(event) { var count = 0; resource.query(function(data) { count = data.length; // accessible here! }); event.id = count; // not accessible here! return resource.save(event); }, getallevents: function() { var count = 0; var lol = resource.query(function(data) { count = data.length; }); console.log(count); return resource.query(); } } });
however, mentioned in comments, i'm unable access length
property. solutions?
by looking @ code getting resource.query
executes callback function asynchronously because of event.id = count;
executed first , callback executed. if want access data.length can use $q
, create defer. , resolve deferred object.