Angular,如何正确映射REST对象

时间:2014-01-20 15:55:48

标签: javascript angularjs

我在角度方面非常新,并且通过我创建的服务从其余调用中映射对象时遇到一些麻烦。

我有服务

var teacherServices = angular.module('teacherServices', ['ngResource']);

teacherServices.factory('Items', ['$resource',
function($resource) {
    return $resource('/class/item/:class_id', {Id: "@Id"}, {
        query: {method:'GET', params:{class_id:''}, isArray:false}
    });
}]);

我正在尝试使用

获取对象列表
teacher_app.controller('ItemsCtrl', ['$scope', '$route', 'Items', function($scope, $route, Items) {
Items.get({class_id : $route.current.params.classId}, function(response) {
    $scope.items = response.items;
    $scope.items[0].$save();  //Does not exist
});

}]);

我有两个问题

1)如何正确映射对象,使其具有所有默认函数,如$ save()

2)如何为对象创建自定义函数

谢谢

1 个答案:

答案 0 :(得分:0)

谢谢Chandermani,你让我思考正确的方向!

问题是我使用的是标准的get方法而不是我在服务中定义的'query'方法。我还将响应调用更改为数组而不是包含数组的对象。

teacherServices.factory('Items', ['$resource',
function($resource) {
    return $resource('/class/item/:class_id', {Id: "@Id"}, {
        query: {method:'GET', params:{class_id:''}, isArray:true}
    });
}]);


teacher_app.controller('ItemsCtrl', ['$scope', '$route', 'Items', function($scope, $route, Items) {
Items.query({class_id : $route.current.params.classId}, function(response) {
    $scope.items = response;
    console.log($scope.items);
});

}]);