angularjscheckboxangularjs-ng-disabled

Enable the Button when any checkbox checked in the loop, Out Side Button


Enable the Button only when any checkbox checked in the loop, the button is out side the loop

HTML

<body ng-controller="MainCtrl">
  <div ng-repeat="$item in items">
    <label>
      Amount: <input type="number" ng-model="$item.amount">
    </label>
    <label>
      Check: <input type=checkbox ng-model="$item.checked">
    </label>
  </div>

  <button type="button" ng-click="checkNow()">Check now</button>

Script :

    function checkNow() {
      $scope.total = $scope.items.filter(function(value) {
        return value.checked;
      }).reduce(function(a, b) {
        return a + b.amount;
      }, 0);
    }

Solution

  • try below code:

    Html
    ----
    
        <body ng-app="main">
          <div  ng-controller="mainCntrl">
           <div ng-repeat="$item in items">
              <label>
               Amount: <input type="number" ng-model="$item.amount">
              </label>
              <label>
               Check: <input type=checkbox ng-model="$item.checked">
              </label>
           </div>
           <button type="button" ng-disabled="disableBtn"  ng-click="checkNow()">Check now</button>
    
        </div>
    
        </body>
    
    
    Controller
    ----------
    
    angular.module('main', [])
    .controller('mainCntrl', function($scope, $timeout) {
      $scope.disableBtn = true;
    
      $scope.items = [{amount: 1200, checked: false},
                      {amount: 1500, checked: false},
                      {amount: 1600, checked: false}];
    
      var isChecked = false;
      $scope.$watch('items', function(newVal) {
         angular.forEach(newVal, function(val) {
             if(val.checked) {
                isChecked = true;
             }
         });
         $scope.disableBtn = !isChecked;
         isChecked = false;
      }, true);
    
    });
    

    It should resolved your issues.

    Cheers!