在循环中选中任何复选框时,启用按钮,外侧按钮

时间:2016-08-11 08:33:11

标签: angularjs checkbox angularjs-ng-disabled

仅在循环中选中任何复选框时启用按钮,按钮位于循环旁边

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

1 个答案:

答案 0 :(得分: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);

});

它应该解决你的问题。

干杯!