ng-repeat:添加新元素的ng-model问题

时间:2018-11-01 13:04:31

标签: angularjs angularjs-ng-repeat

我有输入形式,并使用ng-repeat我用按钮动态添加新的输入字段。 每个输入均已通过“文本”完成。

问题:

当我通过按钮插入新的输入字段时,第一个输入字段会清除文本。

我在浏览器调试器中验证了“ Items Array”的第一个元素是否为空。为什么输入中不存在它?

有我的HTML:

<div class="row">
    <div class="col-sm-10">
        <input ng-repeat="item in vm.myItemsArray" 
        name="myItemName" 
        class="form-control" 
        type="text" 
        ng-model="item.value"/>
    </div>
    <div class="col-sm-1 col-sm-offset-1">
        <span ng-click="addItem()" class="glyphicon glyphicon-plus btn-sm btn-default"/>
    </div>
</div>

AND JS:

// INITIALIZE INPUTS
vm.myItemsArray = [{value: "text"}];

// ADD NEW INPUTS
function addItem() {
    vm.myItemsArray.push({value: "text"});
}

1 个答案:

答案 0 :(得分:0)

(function() {
    'use strict';
    angular
        .module('angularExampleModule',[])
        .controller('angularExampleController', ['$scope', angularExampleController]);

    function angularExampleController($scope){
      $scope.myItemsArray = [{value: "text"}];
      $scope.addItem = function () {
      	$scope.myItemsArray.push({value: "text"});
      }
}
})();
.input-element{
  margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="angularExampleModule" ng-controller="angularExampleController">
<div class="row">
    <div class="col-sm-10 input-element" ng-repeat="item in myItemsArray">
        <input name="myItemName" class="form-control" type="text" ng-model="item.value"/>
    </div>
    <div class="col-sm-1 col-sm-offset-1">
    <button ng-click="addItem()" class="glyphicon glyphicon-plus btn-sm btn-default">Add Item</button>
 
    </div>
</div>

或选中此https://codepen.io/DeepaliK/pen/BqXqNB