Greg
Greg

Reputation: 2690

Angular - how do I use $resource

I have this controller that is working correctly for an Angular UI typeahead. How would I add the server call as a resource?

var receivableApp = angular.module('receivableApp', ['ui.bootstrap', 'ngResource'])
.controller('ReceivableController', function ($scope,$http) {
    $scope.Debtors = function (term) {        
        return $http.get('/Receivable/GetDebtors/?term=' + term).then(function (response) {                
            return response.data;
        });
    };
});

Upvotes: 0

Views: 125

Answers (2)

Rohit Paul
Rohit Paul

Reputation: 336

$resource was meant to retrieve data from an endpoint, manipulate it and send it back.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.var Todo = $resource('/api/1/todo/:id');

//create a todo var todo1 = new Todo(); todo1.foo = 'bar'; todo1.something = 123; todo1.$save();

Upvotes: 0

TeknasVaruas
TeknasVaruas

Reputation: 1510

receivableApp.factory('GetDebtors', ['$resource',
    function($resource){
        return $resource('/Receivable/GetDebtors/');
    }]);

This will add a service GetDebtors with a default GET, and other REST handlers.

Now, to make a call inside your controller, you can do:

debtControllers.controller('DebtCtrl', ['$scope', 'GetDebtors',
    $scope.debts = GetDebtors.get({term: 'foo'});
]);

This is equivalent to making a call to /Receivable/GetDebtors/?term=foo.

If you want to change the behavior, you can override the default methods available on $resource. More details can be found here.

Upvotes: 1

Related Questions