1

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

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

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

小提琴

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");
    };

});
4

1 回答 1

2

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

$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-05-08T14:33:02.073 回答