使用动态ng-model创建动态表单inout字段

时间:2016-05-24 17:51:39

标签: javascript angularjs

我在控制器中有一个JSON对象,我想使用ng-repeat生成动态输入字段。

$scope.keyValuePairs = [
    {id:""},
    {type:""},
    {brand:""},
    {category:""},
    {subCategory:""},
    {division:""}
];

在模板中

<div class="mdl-cell mdl-cell--6-col-desktop mdl-cell--8-col-tablet" 
    ng-repeat="keyValue in keyValuePairs track by $index">
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label full-width" 
        ng-repeat="(key,value) in keyValue">
        <input type="text" id="{{key}}" class="mdl-textfield__input" ng-model="eanForm[key]" 
            name="{{key}}"ng-required="true"/>
        <label class="mdl-textfield__label" for="{{key}}">Enter {{key}}</label>
        <span class="mdl-textfield__error" ng-show="eanForm.id.$dirty && 
            eanForm.id.$invalid" for="{{key}}">{{key}} required</span>
    </div>
</div>

我想创建动态ng模型,以便我可以授予用户添加或删除表单字段的权限。如何将表单字段绑定到动态模型?

1 个答案:

答案 0 :(得分:0)

<强>的Javascript

$scope.fields = [];
$scope.addFields = function() {
    var maxId = getMax($scope.fields, "id");
    var id = maxId ? maxId + 1 : 1;

    $scope.fields.push({
        id: id,
        key: "",
        value: ""
    });
};

$scope.removeField = function(index) {
    if(!index || index < 0) return;

    $scope.fields.splice(index, 1);
}

function getMax(arr, prop) {
    var max;
    for (var i = 0; i < arr.length; i++) {
        if (!max || parseInt(arr[i][prop]) > parseInt(max[prop])) max = arr[
            i];
    }
    return max;
}

<强> HTML

<div ng-repeat="field in fields">
    Field name: <input type="text" id="{{field.id + 'key'}}" ng-model="field.key" />

    Field Value: <input type="text" id="{{field.id + 'value'}}" ng-model="field.value" />
</div>
相关问题