如何从angularjs中的ngform获取数据?

时间:2013-01-29 12:45:48

标签: angularjs

HTML:

<div ng-controller="TestController" >
    <form name="test_form" ng-submit="submit()">
        <input type="text" name="some_name" ng-model="form_data.some_name" required>

        <ng-form ng-repeat="key in keys" name="keyForm">
            <input type="text" name="data_input" ng-model="form_data.data_input" required>
        </ng-form>  

        <a ng-click="addKey()">NEW KEY</a>
    </form>
</div>

JS:

app.controller('TestController', function TestController($scope){

    $scope.keys = [];

    $scope.addKey = function() {
        $scope.keys.push({});
    }

    $scope.submit = function() {
        console.log($scope);
    }

});

在提交功能中,我可以获得“some_name”输入的值:

$scope.submit = function() {
    console.log($scope.form_data.some_name);
}

但是我无法获得“data_input”输入的值(它们位于ngform标签内)。怎么做? (ngform标签用于分别验证每个新添加的输入的能力)

1 个答案:

答案 0 :(得分:4)

ng-repeat中的每个输入都需要自己独特的ng-model属性 - 它们都不能使用form_data.data_input。这是解决问题的一种方法:

<ng-form ng-repeat="key in keys" name="keyForm">
    <input type="text" name="data_input" ng-model="key.data" required>
</ng-form> 

$scope.addKey = function () {
    $scope.keys.push({ data: ''});
}

Fiddle

另见https://stackoverflow.com/a/14379763/215945