我有一个带有一些自定义控件的表单。在这个表单的底部,我需要显示“numSelected of numRequired”。我知道“numRequired”,但我怎么能算“numSelected”?
表单看起来像这样:
<div ng-controller="MyCtrl">
<fieldset ng-repeat="item in items">
<div class="buttons" ng-init="selectedVal=1">
<label>
<input type="radio" name="item{{$index}}" ng-model="selectedVal" value="1" ng-selected="selectedVal==1">
</label>
<label>
<input type="radio" name="item{{$index}}" ng-model="selectedVal" value="0" ng-selected="selectedVal==0">
</label>
</div>
</fieldset>
<div>{{numSelected}} of {{numRequired}}</div>
</div>
我尝试将ng-click
和ng-change
绑定到每个输入并在MyCtrl
进行计数,但我想我不知道如何计算符合条件的项目一旦我'在那里。
答案 0 :(得分:1)
保持范围计数
$scope.count = 0;
$scope.selectedIndex = {};
$scope.count = function (index){
$scope.selectedIndex[index] = 1;
updateCount();
}
$scope.uncount = function (index){
delete $scope.selectedIndex[index];
updateCount();
}
function updateCount(){
var element_count =0;
for (e in $scope.selectedIndex)
{
element_count++;
}
$scope.count = element_count;
}
和ng-click如下
<input type="radio" ng-click="count({{$index}})" name="item{{$index}}" ng-model="selectedVal" value="1" ng-selected="selectedVal==1">
<input type="radio" ng-click="uncount({{$index}})" name="item{{$index}}" ng-model="selectedVal" value="1" ng-selected="selectedVal==1">
在这里显示计数
<div>{{count}} of {{numRequired}}</div>
或您可以使用ng-change直接更改计数
<input type="radio" ng-change={{count + 1}} name="item{{$index}}" ng-model="selectedVal" value="1" ng-selected="selectedVal==1">
<input type="radio" ng-change={{count -1}} name="item{{$index}}" ng-model="selectedVal" value="1" ng-selected="selectedVal==1">