如何从ng-repeat到控制器获取输入值

时间:2016-04-05 20:54:30

标签: javascript jquery angularjs

我有一个表单,当用户点击添加销售按钮时会增加

这是html

<fieldset data-ng-repeat="choice in choices">
    <div class="form-group">
        <label for="name">
            Quantity :
        </label>
        <input type="text" class="form-control" id="choice.quantity" ng-model="choice.amount" />
    </div>

如何在控制器中获取输入值

appcat.controller("MainCtrl", ['$scope',  '$location', function ($scope,  $location)
{
    // this controll the addition and removal
    $scope.choices = [{ 'amount': '' }]; 

    // I want to set the input field
        $scope.choice.amount = parseFloat(200* 4); // $scope.choice.amount and $scope.amount are not working


    // this generate a form
    $scope.addNewChoice = function()
    {
        var newItemNo = $scope.choices.length + 1;

        $scope.choices.push({'amount': ''});

    };

    // this remove the form
    $scope.removeChoice = function () {
        var lastItem = $scope.choices.length - 1;
        if ($scope.choices.length > 1) {
            $scope.choices.splice(lastItem);
        }
    };
}

如何在控制器

中将输入值设置为此计算parseFloat(200* 4);

2 个答案:

答案 0 :(得分:1)

为此,您需要使用ng-model:

来自AngularDocs:

  

ngModel指令使用NgModelController将输入,select,textarea(或自定义表单控件)绑定到作用域上的属性,NgModelController由此指令创建并公开。

链接:https://docs.angularjs.org/api/ng/directive/ngModel

答案 1 :(得分:0)

它可能只是您复制到stackoverflow的代码中的拼写错误,但您应该设置的变量是:

$scope.choices[0].amount = parseFloat(200* 4)

甚至更短:

$scope.choices = [{ 'amount': parseFloat(200* 4}];