cscan
cscan

Reputation: 3840

Creating a new angular $resource

I have a page which is used to create a new resource in our restful web service. The page's controller is as follows:

appController.controller('AddCtrl', ['$scope', 'Person',
        function($scope, $location, Person) {
    $scope.person = new Person();
    $scope.emailList = [];
    $scope.add = function() {
        $scope.emailList.push({email: $scope.email});
        $scope.person.emailList = $scope.emailList;
        $scope.person.$save();
    };
}]);

My service, Person, looks like this:

appService.factory('Person', ['$resource',
    function($resource, uuid){
        return $resource(baseUrl + 'candidate/:uuid', {}, {
            query: {method:'GET', isArray:true},
            get: {method:'GET', params:{uuid: uuid}},
            save: {method: 'POST'},
            remove: {method: 'DELETE', params:{uuid: uuid}}
        });
    }
]);

However, when I view the page, I notice an error at the line:

$scope.person = new Person();

Person is not a function at new <anonymous> ...

And I'm not sure why this is an issue. It was working fine before. I've also tried adding a create method to the service:

appService.factory('Person', ['$resource',
    function($resource, uuid){
        var r = $resource(baseUrl + 'candidate/:uuid', {}, {
            ...
        });
        r.create = function() {
            return $resource(baseUrl + 'candidate', {});
        }
        return r;
    }
]);

However, I receive the following error in my controller:

$scope.person = Person.create();

TypeError: Cannot read property 'create' of undefined at new <anonymous>

Upvotes: 0

Views: 70

Answers (1)

BroiSatse
BroiSatse

Reputation: 44685

The reason is, as it often happen, not where you are looking for it. Problem sits in here:

appController.controller('AddCtrl', ['$scope', 'Person',
    function($scope, $location, Person) {

You have specified two dependencies for your controller, but your function takes 3 arguments - last one will be empty and your Person service got assigned as $location. It should be:

appController.controller('AddCtrl', ['$scope', '$location', 'Person',
    function($scope, $location, Person) {

assuming you are using $location at all.

You will have exactely same issue within your resource - uuid is always null.

Upvotes: 2

Related Questions