引用 ng-repeat 中的 HTML 输入



我有一个关于从(嵌套(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>

最新更新