我的标记上有一个按钮,位于ng-click
,ng-include
模板info.html
上。由于我希望按钮点击发生很多次,ng-include
与单击按钮的次数ng-repeat
相关联 - 范围内的计数器变量:
<div class="form-group">
<label for="info">Info</label>
<button class="btn btn-primary" ng-click="add()">ADD</button>
<hr>
<div ng-repeat="count in sum" ng-include="'info.html'"></div>
</div>
这里info.html
:
<div>
<label for="attribute">Attribute</label>
<input type="text" ng-model="form.info[0].attribute" class="form-control">
<label for="details">Details</label>
<input type="text" ng-model="form.info[0].details" class="form-control">
</div>
基本上info.html
是用于输入键值对的模板,用户可以根据需要输入尽可能多的键值对。这是控制器:
function($scope) {
/** Tracks button clicks, the 1 is for the first
set of key, value inputs to be shown when the form
is initially presented **/
$scope.counter = 1;
// ng-model binding for the form inputs
$scope.form = {};
// This is what will hold the key, value pairs (as objects).
$scope.form.info = [];
/** This array is for simply adding an entry whenever
the button is clicked. I need this array for the ng-repeat **/
$scope.sum = [];
$scope.sum.push($scope.counter);
for (var counter of $scope.sum) {
// Make each element in $scope.form.info an object
$scope.form.info[counter] = {};
}
$scope.add = function() {
$scope.counter++;
$scope.sum.push($scope.counter);
}
}
现在,请注意,在info.html
中,form.info[0].attribute
和form.info[0].details
具有硬编码值0
。我希望这个价值是动态的。我试过了
- form.info[$index + 1].attribute
- form.info[{{$index +1}}].attribute
- form.info[counter].attribute
- form.info[{{counter}}].attribute
但是我得到的是文字字符串,而不是获得数值。作为最后的手段,我写了一个指令:
function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var attribute = 'form.info[' + scope.counter + '].attribute';
var details = 'form.info[' + scope.counter + '].details';
if (attrs.info == 'attribute') {
$(element).attr('ng-model', attribute);
return;
}
if (attrs.info == 'details') {
$(element).attr('ng-model', details);
return;
}
}
}
}
然后应用它(指令的名称为info
)
<input type="text" info="attribute" class="form-control">
<input type="text" info="details" class="form-control">
该指令也不起作用。输入未与form.info
进行双向绑定。不仅如此,这些输入中缺少类ng-pristine
,ng-untouched
,ng-valid
等。
那么如何得到像
这样的结果呢?ng-model="form.info[0].attribute"
ng-model="form.info[0].details"
ng-model="form.info[1].attribute"
ng-model="form.info[1].details"
ng-model="form.info[2].attribute"
ng-model="form.info[2].details"
......等等???
答案 0 :(得分:1)
除非你使用counter
和sum[]
来做其他事情,否则就去除它们。对于你在这里尝试做的事情,它们是不必要的。然后在$scope.add()
函数中,将另一个对象添加到scope.form.info[]
数组。
$scope.add = function() {
$scope.form.info.push({});
}
然后将ng-repeat
改为重复form.info[]
...
<div ng-repeat="obj in form.info" ng-include="'info.html'"></div>
并直接绑定到数组中的每个对象......
<div>
<label for="attribute">Attribute</label>
<input type="text" ng-model="obj.attribute" class="form-control">
<label for="details">Details</label>
<input type="text" ng-model="obj.details" class="form-control">
</div>