0

仅当在循环中选中任何复选框时才启用按钮,按钮在循环之外

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>

脚本 :

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

1 回答 1

2

试试下面的代码:

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

});

它应该可以解决您的问题。

干杯!

于 2016-08-11T10:25:09.630 回答