Search code examples
javascriptrestangularjsangularjs-resource

Why does my Angular resource ignore the action-specific url?


I have the following Angular code:

var app = angular.module('app', ['ngResource']);

app.factory('Post', function ($resource) {
    return $resource('/post', {}, {
        query: { method: 'GET', url: '/post/get/:id', params: { id: '@id' } },
        save: { method: 'POST', url: '/post/addorupdate/:id', params: { id: '@id' } },
        delete: { method: 'POST', url: '/post/delete/:id', params: { id: '@id' } }
    });
});

app.controller('appController', function ($scope, Post) {
    $scope.createPost = function () {
        var post = new Post({
            title: "Test post",
            body: "Test body.<br/ >Yay!"
        });
        post.$save();
    };
});

The markup looks like this:

<body data-ng-app="app">
    <div data-ng-controller="appController">
        <button ng-click="createPost()">Create Post</button>
    </div>
</body>

When I click the button it tries to do a POST to the server, but to the original URL and not the action-specific URL. The URL from the request looks like this:

http://localhost:8080/post?id=undefined

Why is it trying to POST to just /post? Also, any idea why id=undefined? In other examples it seems like ?id=blah just isn't included in the request if the ID isn't specified.


Solution

  • This is a bug in the current version (1.0.8) of AngularJS as of this writing. ngResource is ignoring the url property on action overrides. It was fixed in version 1.1.4 and the fix is present in the latest release candidate (1.2.0).