Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

javascript - AngularJS: count selected items on change

I have a form with some custom controls. At the bottom of this form, I need to display "numSelected of numRequired". I know "numRequired", but how can I figure "numSelected"?

The form looks something like this:

<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>

I've tried tying ng-click and ng-change to each input and doing the counting in MyCtrl but I guess I don't know how to count items which meet conditions once I'm in there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Keep a count in scope

 $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;
    }

and ng-click as below

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

display count here

<div>{{count}} of {{numRequired}}</div>

Or You can directly change count using 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">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...