Angularjs使用不同的url调用实例化的资源方法

时间:2013-03-17 14:39:26

标签: javascript angularjs angularjs-directive angularjs-service angular-resource

我正在尝试使用相同的实例化对象对多个端点进行资源调用。使用原型资源方法的方法确实会更改端点,但@id无法提取。如果我做常规模型,id肯定是对象的属性。$ get,它的工作原理。我感谢任何帮助,我希望代码中的注释能更好地帮助解释。

admin.controller('ModelController', ['$scope', 'Model', function($scope, Model) {

    // first call to instantiate the models with the default resource url
    Model.query(
        {},
        function(resp) {
            $scope.models = resp.results;
        }
    );

    // this event is emited from a directive
    // data is a object from the models collection
    $scope.$on('modelClick', function(event, data) {

        // without this, event fires twice, i am not sure why.
        event.stopPropagation();


        // creates model with resource prototype
        // the hope is then to be able to do $get or $save on $scope.model
        $scope.model = new Model(data);


        // call below will work normal, pulls the id out of the object
        // and sends it with the request to the default url
        $scope.model.$get();


        // this method changes the resource url to the correct one
        // but id=undefined is put on the query string
        // i have debugged the resource api and when this gets called
        // the object is being sent to the $parse method and the id is available
        $scope.model.getInfo();


        // updates the view
        $scope.$apply('model');
    });


}]);


admin.factory( 'Model', ['$resource', function($resource) {

    // default resource url
    var Model = $resource('/:url', {id: '@id', url: 'initial/path'}, {});


    // method to call a different endpoint, but with same id from instantiated object
    Model.prototype.getInfo = function(params, success, error) {
        var response = this.$get(
            {url: 'info/path'}
        );
        return response;
    };

    return Model;

}]);

有关$ scope.model.getInfo()调用/ info / path?id = undefined的原因的任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

我不确定,如果这样可行,但你可以试试吗,

Model.prototype.getInfo = function(params, success, error) {
       var id = this.id; // if id is not a direct member of 'this'. Please inspect the 'this' for any getter method to get the member variables.
        var response = this.$get(
            {url: 'info/path', 'id':id}
        );
        return response;
    };

将此代码放在评论部分可能非常困难,因此添加为答案。