【问题标题】:Dynamically add input fields with Angular and perform validation on blur使用 Angular 动态添加输入字段并对模糊执行验证
【发布时间】:2014-05-08 12:12:04
【问题描述】:

表格在开始时有 1 个地址输入字段。波纹管有一个链接,单击该链接会添加另一个输入,依此类推。字段数量没有限制。

  1. 有没有更优雅的方式在 Angular 的模型集合中添加新元素?我目前正在使用一个空元素数组,在链接上单击我只是在该数组中推送另一个空元素,以便 ng-repeat 将其拾取。当我想提交表单时,我会遍历该数组并过滤掉不为空的元素。

  2. 当输入字段被聚焦/模糊时,应该执行验证。我目前正在 ng-blur 事件上从控制器调用一个函数,但我无法将当前输入文本值传递给它。

Fiddle

HTML:

<div ng-app="TestApp">
    <div ng-controller="MainCtrl">
        <div ng-repeat="field in fields track by $index">
            <input type="text" placeholder="enter the address" ng-model="fields[$index]" ng-blur="validate()" />
        </div>
        <a href="#" ng-click="addField()">+ Add another input</a>
    <br/>
    <br/>
        <a href="#" ng-click="listAddresses()">List addresses</a>
    </div>
</div>

JS:

var app = angular.module("TestApp", []);
app.controller("MainCtrl", function($scope){

    $scope.fields = [null];
    $scope.addresses = [];

    $scope.addField = function(){
        $scope.fields.push(null);
    };

    $scope.listAddresses = function(){
        for(var i in $scope.fields){
            if($scope.fields[i] !== null){
                $scope.addresses[i] = $scope.fields[i];
            }
        }
        alert("Addresses: " + $scope.addresses);
    };

    $scope.validate = function(){
        console.log("Should validate current input");
    };

});

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angular-ngmodel


    【解决方案1】:

    不要使用两个数组,而是使用一个并存储对象:

    $scope.items = 
    [
      { address: '' }
    ];
    

    现在将更清楚输入的模型是什么,因为您不必使用$index。您也可以将项目传递给validate 函数:

    <div ng-repeat="item in items">
      <input type="text" ng-model="item.address" ng-blur="validate(item)" placeholder="enter the address" />
    </div>
    

    添加项目:

    $scope.addItem = function() {
      $scope.items.push({ address: '' });
    };
    

    演示: http://plnkr.co/edit/sPlPO2DfrgNHf5AasYlH?p=preview

    【讨论】:

      猜你喜欢
      • 2014-09-30
      • 2012-07-17
      • 2021-05-21
      • 2018-03-13
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 2017-09-01
      • 2015-12-27
      相关资源
      最近更新 更多