在Angularjs中编写资源

时间:2013-07-15 19:04:19

标签: angularjs

民间,

我很难理解如何在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         
        }); 

}

1 个答案:

答案 0 :(得分:2)

使用角度资源

http://docs.angularjs.org/api/ngResource。$资源

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

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)};

}

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