【问题标题】:Angularjs submit ng-model indexed data to controllerAngularjs 将 ng-model 索引数据提交给控制器
【发布时间】:2016-05-28 13:54:29
【问题描述】:

我是 angularjs 新手,使用 ng-repeat 生成多个选择,如下所示...

                                            <table>
                        <tr ng-repeat="(key, value) in paramMapByCmd">
                        <td></td>
                        <td><input  type="hidden" ng-model="myData.param" value="{{key}}" /><label>{{key}}:</label></td>
        <!--                <td><input type="text" ng-model="myData.param[i]" /></td> -->

                        <td>
                            <select name="param_val_sel" ng-options="item as item for item in value track by $index" 
                                    ng-model="myData.paramValue[$index]"
                                    ng-change="changeParamValue()">
                                <option value="">Select Parameter Value</option>
                            </select>
                        </td>               
                    </tr>    
            </table>

现在当表单被提交时,我如何在控制器中检索数组(希望它是一个数组?)?

$scope.submitCmd = function() {

    var comData = $scope.myData.command;
    use a loop here....
    ????var paramData = $scope.tl1Data.paramValue[$index]; ????

你是怎么做到的?

附:我添加了更多的 html 来显示 ng-repeat...

【问题讨论】:

  • 你能用html显示完整的表格吗?!
  • 通常您会将表单ng-model 中的所有内容绑定到一个对象,每个ng-model 都有自己的属性,然后将该包含整个表单数据的对象发送到服务器
  • $index 变量是一个特殊值,仅存在于 view ng-repeat 指令中。不能在控制器中使用。
  • 我不确定 $[index ] 做了什么来将数据发送回 Angular 控制器。选择是从 LinkedHashMap> ... $scope.paramMapByCmd = result; 动态创建的

标签: angularjs select indexing ng-repeat


【解决方案1】:

在您的控制器$scope.tl1Data.paramValue 中已经存储了一个数组。 要对其进行迭代,您可以执行以下操作:

for(item in $scope.tl1Data.paramValue) {
    console.log(item);
}

【讨论】:

    【解决方案2】:

    这是ng-options的简单示例

    控制器

    app.controller('MainCtrl', function($scope) {
    
      $scope.items = [];
      $scope.selectedItem = {};
      $scope.items = [{name: 'one', id: 30 },{ name: 'two', id: 27 },{ name: 'threex', id: 50 }];
    });
    

    查看

    <body ng-controller="MainCtrl">
      <p>selected item is : {{selectedItem}}</p>
    
      <p> name of selected item is : {{selectedItem.name}} </p>
    
      <select ng-model="selectedItem" ng-options="item.name for item in items track by item.id"></select>
    </body>
    

    在这种情况下,您选择的结果将在 $scope.selectedItem 中。这意味着您的结果应该在您放入ng-model的变量中

    Here is the plunker with example

    在您的情况下,您不需要在$index 在ng-model中,您可以像这样保持ng-model="tl1Data.paramValue",然后在控制器中检查您的范围 喜欢console.log($scope.tl1Data.paramValue)

    【讨论】:

      猜你喜欢
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多