0

伙计们,

我很难理解如何在 AngularJs 中编写资源。我目前编写了一个工厂方法,如下所示:

var baseUrl = "http://www.myBaseUrl.com/cgi-bin/angular-portal/backend.pl";

   myApp.factory('Employee',['$http',function($http){
var employeeUrl = baseUrl + "?getemployeelist";
return{
query: function(){
    return $http.get(employeeUrl);
},
get: function(empId) {
    return $http.get(employeeUrl + '=' + empId)
}
}; 
]);

如何在其中包含 POST 调用?目前我直接在控制器中进行 POST 调用,据我所知,这不是这样做的方法:

function EmployeeAddCtrl($scope,Employee,$routeParams) {
// Add a new employee
$scope.addOrUpdate = function() {

var jsonString = angular.toJson($scope.employee);

    //Make the REST call
    $http.post(postUrl,jsonString)
        .success(function(data,status,headers,config) {
    // show success message here
         })
        .error(function(data,status,headers,config){
    // DO SOMETHING HERE.. FIGURE LATER         
        }); 

}
4

1 回答 1

2

使用角度资源

http://docs.angularjs.org/api/ngResource .$resource

这样你就可以在服务中做这样的事情:

mainApp.factory('ObjectService', function($resource,$location) {

    var Object = $resource('/admin/object/:id',{id:'@id'},
        {update: {method:'PUT', params:{id:'@id'}}}
    );

    Object.redirect = function(data){
        $location.path('/index');
    };

    Object.fail = function (e){
        alert('Alert Something went wrong')
    };
    Object.new = function(){
        return new Object();
    }
    return Object;
});

然后像这样在控制器上调用它:

function PromocionController($scope,$routeParams,ObjectService){

    if($routeParams.id){
        $scope.object = ObjectService.get({id:$routeParams.id});
        $scope.save = function(){$scope.object.$update({id:$scope.object.id},ObjectService.redirect,ObjectService.fail)};
    } else {
        $scope.object = ObjectService.new();
        $scope.save = function(){$scope.object.$save({id:$scope.object.id},ObjectService.redirect,ObjectService.fail)};
    }

    $scope.delete = function(){$scope.object.$remove({id:$scope.object.id},ObjectService.redirect,ObjectService.fail)};

}

请注意两件事。1)你可以让它变得更简单我制作了像更新方法这样的自定义方法,并向删除和保存方法添加了参数,以使其与 Laravel 资源控制器一起工作。2)我在服务中添加了失败和重定向功能只是为了可重用性,如果你想要一个更简单的例子,请阅读:AngularJS $resource RESTful example

于 2013-10-30T15:47:19.263 回答