如何使用ng-model和ng-repeat(在表单中)绑定数据

时间:2016-02-09 22:51:51

标签: angularjs binding

我有一个角度范围变量,它是一个对象数组并绑定到一个表单组,当单击一个按钮时,它会创建一个用户可以填写的新表单组。每个表单组包含两个字段名称和编号。我试图弄清楚将表单中的表单字段绑定到数组中对象中的数据。只是因为没有任何意义,我想要一个具有动态数量的字段的表单,这些字段绑定到范围内的数组中的对象。

这是我的代码

在控制器中;

    $scope.choices = [{name: 'thename1', number:"10"}];


    // This function adds aditional nutrients
    $scope.addChoice = function() {
        var newItemNo = $scope.choices.length+1;
        $scope.choices.push({'name':'choice'+newItemN, number""});
        console.log(JSON.stringify$scope.choices));
    };

在我看来,我有以下代码

                    <fieldset data-ng-repeat="choice in choices">
                        <legend>Choice</legend>
                        <!-- START row -->
                        <div class="row" >
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Name</label>
                                    <input type="text" ng-model="choice.name" name="name" placeholder="Test" class="form-control" />
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Target Volume (ml/l)</label>
                                    <input type="text" ng-model="choice.number" name="target-volume" placeholder="132" class="form-control" />
                                </div>
                            </div>
                        </div>
                        <!-- END row -->
                    </fieldset>
                    <div> Testing
                        <button type="button" class="mb-sm btn btn-pink"  ng-click="addChoice()">Add Another Choice</button>
                    </div>

修改

好吧所以它按预期工作,但是当我尝试保存结果时,如果我有一个创建函数,它就失败了

    $scope.create = function() {
        console.log('this.choices' + JSON.stringify(this.choices));

}

第一个控制台日志记录正确的对象,而创建函数中的对象则不记录。我错过了什么吗?我也在第二个函数中尝试了$ scope.choices,但它不起作用

2 个答案:

答案 0 :(得分:0)

Here正在使用普兰克。

只有几个拼写错误:

$scope.choices.push({'name':'choice'+newItemNo, number: 10});

当你有:

$scope.choices.push({'name':'choice'+newItemN, number""10});

newItemN未定义,number""10 - 无效语法

答案 1 :(得分:0)

只需将一个新变量推送到数组即可。即使是空物也足够了。见下面的实现

&#13;
&#13;
tf labels
&#13;
var app = angular.module('myApp', []);

app.controller('formController', function($scope) {
  $scope.choices = [{}];

  $scope.addChoice = function() {
    $scope.choices.push({});

    console.log($scope.choices);
  };

  $scope.submitChoices = function() {
    console.log($scope.choices);
    $scope.submittedChoices = angular.copy($scope.choices);
  };
});
&#13;
&#13;
&#13;