如何将控制器中的查询参数传递给angularjs中的服务?

时间:2014-03-07 11:42:23

标签: angularjs rest angularjs-directive angularjs-scope angularjs-ng-repeat

我有一个表单,我在其中使用ng-click提交文本,现在它调用休息服务并插入数据库 - 工作正常。同时,在同一个函数中,它调用另一个休息服务但没有发生任何事情,我想知道如何将参数传递给服务???

Controller.js

                app.controller('MyCtrl1', ['$scope', 'PostFactory', '$location', function ($scope, PostFactory, $location) {

                /* callback for ng-click 'createUser': */
                $scope.createPost = function () {
                    alert("in createPost" + $scope.UserPost.postText);
                    alert("in createPost" + $scope.UserPost);
                    PostFactory.postmain.create($scope.UserPost)
                    $scope.allposts.push($scope.UserPost);
                    $scope.UserPost = "";
                    $scope.allresultsfinal = PostFactory.allresults.query({tag: $scope.UserPost.postText})
                    $location.path('/view1');
                }

                $scope.allposts = PostFactory.postmain.query();


                /*UserFactory.get({}, function (userFactory) {
                 $scope.firstname = userFactory.firstName;
                 })*/
            }]);

Services.js

            'use strict';

            /* Services */

            var services = angular.module('ngdemo.services', ['ngResource']);
            //alert("In services");
            services.factory('PostFactory', ['$resource', function ($resource) {
                return  {

                    postmain: $resource('/ngdemo/web/posts', {}, {
                        query: {method: 'GET', isArray: true },
                        create: {method: 'POST'}
                    }),
                    allresults: $resource('/ngdemo/web/posts/result/:tag', {id: '@id'}, {
                        query: {method: 'GET', params: {id: '@id'}, isArray: true },
                        create: {method: 'POST'}
                    })};
            }]);

在所有结果中,id没有来,或者我不知道controll是否到达这里。在“postmain”中提交帖子并且查询工作正常。请让我知道怎么做?

我需要在控制器中发送“#scope.UserPost.postText”的“tag”作为参数

$scope.allresultsfinal = PostFactory.allresults.query({tag: $scope.UserPost.postText})

到service.js“allresults”并从休息服务中获取数据。

2 个答案:

答案 0 :(得分:2)

您传递给未明确指定的服务函数的任何内容总是作为查询参数添加,因此您只需要执行以下操作:

allresults: $resource('/ngdemo/web/posts/result/:tag', {tag: '@tag'}, {  
`query: {method: 'GET',   
`params: {},   
`isArray: true },  
`create: {method: 'POST'}  
})};  

然后像这样称呼它

$scope.allresultsfinal = PostFactory.allresults.query(  
`{tag: $scope.UserPost.postText,  
`id:$scope.someId}//perhaps $routeParams.id ??  
`);

答案 1 :(得分:0)

尝试下面的内容,

allresults: $resource('/ngdemo/web/posts/result/:tag', {}, {
     query: {method: 'GET', isArray: true },
     create: {method: 'POST'}
})};

在控制器中

$scope.allresultsfinal = PostFactory.allresults.query({tag: $scope.UserPost.postText})