AngularJS:计算所选项目的变化

时间:2013-12-31 20:14:29

标签: javascript angularjs

我有一个带有一些自定义控件的表单。在这个表单的底部,我需要显示“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-clickng-change绑定到每个输入并在MyCtrl进行计数,但我想我不知道如何计算符合条件的项目一旦我'在那里。

1 个答案:

答案 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">