【问题标题】:How to dynamically add a new input if other are filled Angular如果其他已填充Angular,如何动态添加新输入
【发布时间】:2016-02-16 20:48:38
【问题描述】:

我有三个输入:

<input type="text" class="form-control" id="friend-email-input" placeholder="Email" />
<input type="text" class="form-control" id="friend-email-input" placeholder="Email" />
<input type="text" class="form-control" id="friend-email-input" placeholder="Email" />

如果这三个输入和先前的输入都已填充,如何添加新输入? 我正在使用角度路线,我宁愿使用 Angular。

谢谢。

【问题讨论】:

    标签: javascript angularjs input


    【解决方案1】:

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app>
        <input type="text" class="form-control" ng-model="field1" placeholder="Email" />  
        <input type="text" class="form-control" ng-model="field2" placeholder="Email" />
        <input type="text" class="form-control" ng-model="field3" placeholder="Email" />
        <input ng-show="field1.length && field2.length && field3.length" type="text" class="form-control" ng-model="field4" placeholder="Email" />
    </div>

    为每个输入分配一个模型,然后如果模型的长度为真(即:非零),则使用 ng-show 仅显示第 4 个输入。

    【讨论】:

      【解决方案2】:

      在您的控制器中跟踪您需要的所有输入,从

      开始
      $scope.inputs = [{value: ""}, {value: ""}, {value: ""}];
      

      在您的模板中,您将迭代此数组以显示您拥有的输入

      <div ng-app="main" ng-controller="MainController">
        <div ng-repeat="input in inputs track by $index">
          <input type="text" class="form-control"  placeholder="Email" ng-model="input.value"/>
          <button ng-click="remove($index)">Remove</button>
        </div>
        <button ng-click="addInput()">Add Input</button>
      </div>
      

      因此,当单击输入的删除按钮时,如果存在超过 3 个输入,则该输入将被删除

      如果按下添加输入按钮,我们会附加一个带有删除按钮的输入文本

      $scope.remove = function(index){
        if($scope.inputs.length > 3){
          $scope.inputs.splice(index, 1);  
        }
      }
      
      $scope.addInput = function(){
          $scope.inputs.push({value: ""})
      }
      

      这是一个例子codepen

      【讨论】:

      • 非常感谢!但是如果以前的输入很脏,如何添加新输入?以及如何首先显示 3 个输入,如果其中一个被填充,接下来如何生成新的?
      • @user3313798 我更新了 codepen 示例,包括一个用于删除每个输入的按钮和一个用于添加输入的按钮。至少应存在 3 个输入
      猜你喜欢
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多