2013-04-05 34 views
1

我是AngularJS的新手,但现在已经使用Backbone了一段时间。如何将模型名称传递给angularJS restful api

我想创建一个可重复使用的restful api,我可以将模型名称传递给我,以便我可以将它用于不同的模型。

目前我有:

angular.module('healthplanApiServices', ['ngResource']) 
.factory('Api', function($resource) { 
    return $resource(base_url + 'api/:object/:id', { 
      id : '@id', object : 'actions' 
    }, { 
     query : { 
      method : 'GET', 
      isArray : true, 
      callback : "JSON_CALLBACK" 
     }, 
     save : { 
      method : '@id' ? 'PUT' : 'POST', 
      isArray : true, 
      callback : "JSON_CALLBACK" 
     } 
    }); 
}); 

...这台型号为 '动作'。然后在我的控制器使用:

// get the collection 
Api.query(function(r) { 
$scope.actions = r; 
}); 
$scope.toggleDone = function(a) { 
    a.done = !a.done; 
    //save an item 
    Api.save(a); 
} 

这一切很好,但如何通过型号名称(在这种情况下,“行动”),为每个模型类型:例如,而不是把它在工厂之类的函数所以:

id : '@id', object : 'actions' 

...而是更多的东西一样:

var ActionApi = Api.setObject('actions'); 
ActionApi.query(function(r) { 
    $scope.actions = r; 
}); 

更新: 我只是想出了一个办法。它可能不是最好的,但它确实有效。任何其他建议将受到欢迎! 就在“对象”属性添加到模型:

Api.query({object: 'actions'}, function(r) { 
    $scope.actions = r; 
    angular.forEach($scope.actions, function(a) { 
    a.object = 'actions' }); 
    }); 
Api.save(a);// also works 
+0

这是将参数传递给后端预期的方式。请放心,你正在做正确的事情;) – alx 2013-05-11 13:50:52

回答

0

你可能想尝试https://github.com/klederson/ModelCore(ModelCore)

它易于模式和结构,当然...使用。

model.$find({ filter : "John" },{},true); //to find all with query parameters 
model.$get(1); //to retreive the user with id 1 
model.$save() 
model.$deelte(); 

等等..检出文档

+0

你可以在这里找到更多:http://stackoverflow.com/a/16672594/1558820 – 2013-05-22 00:34:50

相关问题