【问题标题】:ng-repeat : ng-model problem adding new elementng-repeat : 添加新元素的 ng-model 问题
【发布时间】:2018-11-01 13:04:31
【问题描述】:

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

问题:

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

我在浏览器调试器中验证,我的 Items Array 的第一个元素不为空。为什么它没有出现在 input 上?

这是我的 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>

和 JS :

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

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

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    (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

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2015-08-13
      • 2017-11-19
      相关资源
      最近更新 更多