0

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

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Can we write one or more $scope.$watch function in single controller.?
yes but try to avoid as much as possible since it will decrease the performance.
i Like the Logic, but u have implemented in ngClick. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.