我有一个问题要从ng重复(嵌套)生成的输入标签中获取信息。
我有嵌套对象,可以使用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?
答案 0 :(得分:0)
不确定要做什么,但是请检查一下是否有帮助:
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>