AngularJS计数ngResource返回的文件夹中的对象 [英] AngularJS Counting objects in a folder returned by ngResource
问题描述
我正在学习AngularJS,我想我可能是一个简单的问题.
I am learning AngularJS and I have what I imagine is probably a simple issue.
我正在使用$ Resource从文件夹中获取json对象,并且需要对文件夹中的对象进行计数.我已经能够在save函数中的回调语句中获得所需的值,但是我做错了什么,因此无法将其返回到需要使用的位置.我正在使用计数作为一种为文件夹中创建的文件自动增加ID的方法.
I am using $Resource to get json objects from a folder, and need to have a count of the objects in the folder. I have been able to get the value I am looking for in a callback statement within the save function, but I am doing something wrong, and I am unable to return it to where I need to use it. I am using the count as a way to auto increment the ID's for the files created in the folder.
我在代码中有注释,说明可以在何处访问该值以及需要在何处访问它,所有这些均在保存功能内.
I have comments in the code as to where I can access the value, and where I need to access it, its all within the Save Function.
任何帮助将不胜感激.
我的服务:
eventsApp.factory('eventData', function($resource) {
var resource = $resource('/data/event/:id', {id: '@id'}, {"getAll": {method: "GET", isArray:true, params: {something: "foo"}}});
return {
getEvent: function(eventId) {
return resource.get({id:eventId});
},
save: function(event) {
resource.query(function(data){
console.log("Event ID In: " + data.length); //value is accessible here
});
event.id = ; //need to access value here
return resource.save(event);
},
getAllEvents: function() {
return resource.query();
}
};
});
谢谢
推荐答案
您可以这样做,而无需在$ resource周围使用包装器
You can do it like that, without the need of a wrapper around $resource
eventsApp.factory('eventData', function($resource) {
return $resource('/data/event/:id');
});
然后在您使用工厂的地方(例如控制器代码),可以为此功能定义一个函数
Then in the place you use your factory (e.g. controller code), you can define a function for this behavior
function saveEvent(event) {
eventData.query(function(data){
console.log("Event ID In: " + data.length); //value is accessible here
event.id = data.length;
eventData.save(event);
});
}
但是我认为您应该重新考虑数据库设计.对我而言,始终将保存与查询连接似乎不是一个有效的解决方案.
But I think you should reconsider your database design. Connecting a save with a query all the time seems not like an efficient solution to me.
这篇关于AngularJS计数ngResource返回的文件夹中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!