簡體   English   中英

創建一個在AngularJS中輸入時重復的文本框?

[英]Making a text box that duplicates upon input in AngularJS?

我正在嘗試制作一系列文本框。 它以一個文本框開始,但是當用戶將信息放入其中時,另一個空文本框將顯示在其下方。 這將無限期地繼續下去。

每個文本框都需要具有與之關聯的ng-model值,並且每個文本框都需要由ng-repeat生成。

例如,我的HTML是這樣的:

<table ng-controller="BoxesController">
  <tr ng-repeat="box in boxes">
    <td><input type="text" ng-model="box.input"></td> <!--boxes[0].input-->
  </tr>
</table>

我使用box.input而不是box因為它還需要分配其他變量。

然后我的控制器將是:

.controller('BoxesController',['$scope',function($scope){
  $scope.boxes = [
    {input: ""}
  ];

  if($scope.boxes[$scope.boxes.length - 1] !== ""){
    $scope.boxes.push({input: ""});
    $scope.$apply;
  }
}])

這將在其中box.input === ""的視圖中創建一個空框。 if基本上是“如果數組中的最后一個值不為空,則將新的空值附加到數組中”。

最初,整個過程應該創建一個空框,然后在用戶逐框輸入數據時生成更多框。

但是,它實際上所做的是生成兩個完全不響應輸入的空框。

有人會在這里做什么,如何使這項工作嗎?

謝謝!

將條件包裝在方法中:

$scope.newBox = function() {
   if($scope.boxes[$scope.boxes.length - 1].input !== ""){
    $scope.boxes.push({input: ""});
    console.log( $scope.boxes)
    $scope.$apply;
  }
};

HTML:

<td><input type="text" ng-model="box.input" ng-blur="newBox()"></td>

演示版

作為上面的答案,請嘗試使用一種方法。 這是另一個使用ng-change的示例。

 angular.module('app',[]) .controller('BoxesController',['$scope',function($scope){ $scope.boxes = [ {} ]; $scope.callChange = function() { if($scope.boxes[$scope.boxes.length - 1].val !== ""){ $scope.boxes.push({val: ""}); } }; }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='app'> <table ng-controller='BoxesController'> <tr ng-repeat="box in boxes"> <td><input type="text" ng-model="box.val" ng-change="callChange()"></td> </tr> </table> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM