runtimeZero
runtimeZero

Reputation: 28076

Writing Resources in Angularjs

Folks,

I am having a hard time understanding how to write a resource in AngularJs. I have currently written a factory method as below:

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

How do I include a POST call in this ? Currently I am making a POST call directly in the controller and as I understand this is not the way to do it:

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

}

Upvotes: 0

Views: 440

Answers (1)

Gabriel Acosta
Gabriel Acosta

Reputation: 111

Use Angular Resource

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

this way you can do something like this in a service:

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

And then Call it on a controller like this:

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

}

Please note 2 things. 1) You could make this a lot simpler I made custom methods like the update method and added parameters to the delete and save method to make it work with Laravel Resource Controller. 2) I added the fail and redirect functions in the service just for reusability purposes, if you want a simpler example please read this: AngularJS $resource RESTful example

Upvotes: 2

Related Questions