【问题标题】:How to get input value from dynamically created input box within a table using ng-repeat?如何使用 ng-repeat 从表中动态创建的输入框中获取输入值?
【发布时间】:2018-11-24 20:42:42
【问题描述】:

如何使用 ng-repeat 从表格中动态创建的输入框中获取输入值?我的 html 中有这段代码:

   <table class="table table-striped" name="progressLogTable">
          <thead>
              <th>Title</th>
              <th>Input</th>
          </thead>
          <tbody>
             <tr ng-repeat="x in progressLog track by $index ">
                <td>{{x}}</td>
                <td><input type="number" ng-model="dataInput[$index]"></input></td>
             </tr>
          </tbody>
   </table>

我需要单击按钮时生成的文本框内的值。到目前为止,这是我的 JS:

 $scope.gettingInputDataFromTrackables = function(){
      $scope.dataInput =[];
  }

我尝试使用 $index 动态创建每个输入的模型,但我认为我使用不正确。我还尝试将我的td 生成为:

<td>{{x}}</td>
<td><input type="number" ng-model="progressLog[$index]"></input></td> 

但是当我这样做时,它会将我的标题标题绑定到该索引处输入框的值。总而言之,我只需要与标题对应的输入框的值,该标题也是动态添加到ng-repeat 中的。

【问题讨论】:

  • 当您按下提交按钮时,$scope.dataInput 里面是什么?它怎么不工作?
  • 当我在提交函数中执行console.log($scope.dataInput); 时,它会记录一个空数组,与动态创建的输入框的值相对应。
  • 对不起,这根本不是您所要求的,但我会以简单的角度让您进入:将模型粘贴到您正在迭代的对象上。例如:ng-model="x.dataInput"。一旦您想添加/删除任何项目,track by $index 也会变得如此古怪。只需确保您的正在进行的项目Log-items 有一个具有唯一值的正确 id 字段并执行ng-repeat="x in progressLog track by x.id",这将为您省去很多麻烦。再说一次,不是你要的——对不起!
  • 我不知道为什么我没有想到为这个“ng-repeat”做那个我为我项目中的其他每个人做的。谢谢你提醒我!
  • 解决方案发布在下面。

标签: javascript html angularjs


【解决方案1】:

嗯,这是一个简单的修复。在我的函数内部:

$scope.gettingInputDataFromTrackables = function(){
      $scope.dataInput =[];
      console.log($scope.dataInput);
  }

每次单击时我都在初始化$scope.dataInput = [],导致数据被清除并且我记录了一个空数组。这在很长一段时间内都没有击中我。 解决方法是

     $scope.dataInput =[];
     $scope.gettingInputDataFromTrackables = function(){          
              console.log($scope.dataInput);
          }

是的,仅此而已。我刚刚在函数范围之外声明了$scope.dataInput。简单的错误和更容易的修复。

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 2017-01-30
    • 2012-08-16
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多