如何在AngularJS中使用$resource在URL查询字符串中传递HTML表单字段中的数据

How to pass data from HTML form fields in a URL query string using $resource in AngularJS?

本文关键字:HTML 表单 字段 字符串 数据 URL AngularJS resource 查询      更新时间:2023-09-26

我正在为使用Jersey API开发的基于REST的服务器端应用程序设计UI。我想从HTML表单中获取输入,并将数据作为查询字符串参数传递,以构建REST URL。我也浏览了AngularJS文档,但没有找到我问题的答案。我知道$资源用于GET/POST/PUT请求,我知道我们可以使用$resource用查询字符串构建URL。谁能指导我如何从表单字段传递查询字符串参数?

在HTML中创建一个输入字段和添加数据的按钮

<div  ng-controller="myCtrl">
 <input ng-model="item.name" />
 <button ng-click="addItem()">Add Item</button>
</div>

创建调用API的Service

   var myApp = angular.module("myApp",['ngResource'])
   myApp.factory("myService", function ($resource) {
        return $resource(
            "http://localhost/items/:id",
            {id: '@id'},
            {
                update: { method: 'PUT' },
                query: {method: 'GET', isArray: true},
                get: {method: 'GET'}
            }
        )
    })

创建控制器

   myApp.controller("myCtrl", function ($scope, myService) {
   $scope.Details = myService.get();
   $scope.addItem = function () {
   myService.save($scope.item, function (data) {
        $scope.Details.push(data);
        $scope.item = {};
      });
   };