在 ng-repeat 中引用 html 输入

referencing an html input within ng-repeat

我有一个关于从(嵌套的)ng-repeats 中生成的输入标签中获取信息的问题。

我有嵌套对象,这些对象通过使用 ng-repeat 进行迭代。在最内层,我需要获取密钥,并将其附加到用户输入的值。 (它是 属性 的名称以及对其进行采样的频率。)但是,我似乎无法访问输入字段的值。

我很乐意直接传递值,而不必像这样为输入提供 ID:

<div class="well" ng-show="showProps == true" ng-repeat="(key, value) in obj">
  <h5><strong>{{key}}</strong></h5> 
  <h5>Sample Interval:</h5>
  <input id="period" class="form-control" type="number" value="20" step="10" />
  <button ng-click="addToList(device,obj,key,period.value)">add</button>
  <button ng-click="removeFromList(device,obj,key)">remove</button>
</div>



  $scope.addToList = function(device,obj,prop,period) {
    console.log("Sample period: " + period);
  }

但是,这给了我一个未定义的错误,所以我尝试用 {{$index}} 变量给它一个 id,然后在 javascript 中引用它。

<div class="well" ng-show="showProps == true" ng-repeat="(key, value) in obj">
  <h5><strong>{{key}}</strong></h5> 
  <h5>Sample Interval:</h5>
  <input id="period_{{$index}}" class="form-control" type="number" value="20" step="10" />
  <button ng-click="addToList(device,obj,key,{{$index}})">add</button>
  <button ng-click="removeFromList(device,obj,key)">remove</button>
</div>



  $scope.addToList = function(device,obj,prop,period_index) {
    var per = document.getElementById("peroid_{{$perod_index}}").value
    console.log("found a function: " + per);
  }

但是,这给了我一个解析错误,所以我觉得我找错了树。我如何从那里获取价值并进入 javascript?

不太确定你想做什么,但检查一下看看是否有帮助:

angular.module("app", [])
.controller('MainCtrl', function ($scope)
{
  $scope.showProps = true;
  $scope.items = [];
  $scope.obj = {
    "first": {
      input: 20,
      items: []
    },
    "second": {
      input: 20,
      items: []
    }
  };
  
  $scope.addToList = function(key,value)
  {
    $scope.obj[key].items.push(value);
  };
  
  $scope.removeFromList = function(key, value)
  {
    var index = $scope.obj[key].items.indexOf(value);
    
    if(index != -1)
    {
     $scope.obj[key].items.splice(index, 1);
    }
    
  };
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
  <div class="well" ng-show="showProps == true" ng-repeat="(key, value) in obj">
    <h5><strong>{{key}}</strong></h5> 
    <h5>Sample Interval:</h5>
    <input class="form-control" type="number" step="10" ng-model="value.input" />
    <button ng-click="addToList(key,value.input)">add</button>
    <button ng-click="removeFromList(key, value.input)">remove</button>
    <span ng-repeat="item in value.items track by $index"><br>{{item}}</span>
  </div>
</div>
</body>
</html>