【问题标题】:Sending data form ng-repeat从 ng-repeat 发送数据
【发布时间】:2014-12-24 02:07:53
【问题描述】:

我有一个使用 ng-repeat 模块构建的表单:

form-{{$index}}-id
form-{{$index}}-value

这是表单的 HTML:

<input type="text" id="form-0-id" />
<input type="text" id="form-0-value />
<input type="text" id="form-1-id" />
<input type="text" id="form-1-value />

我需要将输入文本值作为表单数据发送,而不是作为查询字符串。 我必须使用 AngularJS 来做到这一点,我不能使用旧的经典按钮和 POST 刷新。

FORM DATA

form-0-id:"x"
form-0-value:"y"
form-1-id:"a"
form-1-value:"b"

除...

我怎样才能做到这一点? 我已经有一个将数据从查询字符串转换为表单数据的函数:

app.config(function($httpProvider) {

    // Use x-www-form-urlencoded Content-Type
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function(data)
    {
        return angular.isObject(data) && String(data) !== '[object File]' ? jQuery.param(data) : data;
    }];

}); 

【问题讨论】:

    标签: angularjs forms post angularjs-ng-repeat


    【解决方案1】:

    我认为您可能使这个问题过于复杂,您有一个要 POST 回服务器的项目列表。

    定义一个控制器来管理这个列表,并通过ng-submit处理发布操作

    var module = angular.module('testApp', []);
    
    module.controller('MyCtrl', function($http){
      var self = this;
      self.items = [
        {prompt: 'prompt 1', value: 'value 1'},
        {prompt: 'prompt 2', value: 'value 2'},
        {prompt: 'prompt 3', value: 'value 3'}
      ];
      
      self.submitMe = function(){
        var url = 'http://serverUrl'
        
        //sample post code:
        //$http.post(url, self.items);
        
        //debug:
        alert('post data to ' + url + '\n' + JSON.stringify(self.items));
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="testApp" ng-controller="MyCtrl as my">
    <form ng-submit="my.submitMe()">
      <ul>
        <li ng-repeat="item in my.items">
          {{item.prompt}} <input type="text" ng-model="item.value"/ >
        </li>
      </ul>
      <button>Save</button>
    </form>
      </div>

    【讨论】:

    • 首先感谢您的回答。您的答案中有一个主要问题:结构。您具有相同的结构,由两个字段组成:提示和值。我想发布类似 form-0-id: a, form-0-value: b; 的内容form-1-id: c, form-1-value: d 等等......我不知道如何获得这样的结构。
    • promptvalue 是两个不同的值,我只是将它们键入相同,它们可以是您想看到的任何值,我会更新以反映这一点。跨度>
    • 但是我怎样才能只向服务器发送物品的价值呢?我的意思是,我严格需要这样的数据:form-1:x,form-2:y ecc ...在键值结构中,问题不是值而是键,它必须是动态的,就像我之前显示(KEY -> form-1 VALUE -> X, form-2 ; y exc...)使用你的方法我怎么能得到它?
    • 在我的示例中,您可以将发布到服务器的值映射为您需要的任何格式。它捕获提交事件,您可以在那里创建适合您需求的新数据结构。
    • 感谢您的回复;)我如何映射它们?我应该使用之前发布的 transformRequest 吗?
    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    相关资源
    最近更新 更多