如果在Angular JS中未选中复选框,则禁用按钮

时间:2017-03-31 13:55:16

标签: javascript angularjs

所以我正在处理这个Web应用程序。我有一个类别列表,如果未选中列表中的项目,将禁用"保存"和#34;发布"按钮。我理解val doubleUdf: UserDefinedFunction = udf((v: Any) => Try(v.toString.toDouble).toOption) 会做到这一点,但每次我加载页面时,按钮都会被禁用,但是当我检查列表中的项目时却没有启用。

ng-disabled = !(ng-model name)

JS代码:

<a ng-if="status() < 2" href="#" data-ng-click="publish(true)" class="btn btn-sm btn-block btn-success" ng-disabled="!cat.IsSelected">{{lbl.publish}}</a>
<a ng-if="status() == 2" href="#" data-ng-click="save()" class="btn btn-sm btn-block btn-primary" id="check_box" ng-disabled="!cat.IsSelected">
{{lbl.save}}
</a>                       
<span ng-if="status() < 2">
   <a href="#" ng-click="save()" class="btn btn-sm btn-block btn-primary"   id="check_box" ng-disabled="!cat.IsSelected">
    {{lbl.save}}
   </a>
</span>

<ul class="categories-list">
    <li ng-repeat="cat in lookups.CategoryList">
      <label><input type="checkbox" id="cat-{{cat.OptionValue}}" data-ng-model="cat.IsSelected"/> {{cat.OptionName}}</label>
    </li>
    <li ng-if="lookups.CategoryList.length == 0" class="item-empty">{{lbl.empty}}</li>
</ul>

1 个答案:

答案 0 :(得分:2)

UPDATE:让小提琴更像实际情景。

<a>标记包裹在一个按钮中并将ng-dissabled放在该标记上。

这是一个演示如何执行此操作的小说:fiddle

<div ng-app="test" ng-controller="myController">
  <button ng-click="save()" ng-disabled="!hasSelectedAnItem" class="btn btn-sm btn-block btn-primary">
    Save
  </button>
  <ul class="categories-list">
      <li ng-repeat="cat in items">
          <label><input type="checkbox" id="cat-{{cat.OptionValue}}" ng-model="cat.IsSelected" ng-change="canBeSaved()"/> {{cat.OptionName}}</label>
      </li>
  </ul>
</div>

JS:

angular.module('test', [])

.controller('myController', ['$scope', function($scope) {
    $scope.hasSelectedAnItem = false;

   $scope.items = [
        {OptionValue: 123, OptionName: "Adam", IsSelected: true},
      {OptionValue: 234, OptionName: "Paul", IsSelected: false},
            {OptionValue: 345, OptionName: "Jason", IsSelected: true},          
      {OptionValue: 464, OptionName: "Joe", IsSelected: false}
   ];

   $scope.canBeSaved = function() {

      var found = false;
        $scope.items.forEach(function(item) {
        if (item.IsSelected) {
            alert("Here");
            found = true; 
        }
      });

      $scope.hasSelectedAnItem = found;
   }

   $scope.save = function() {
        alert($scope.cat.IsSelected);
   }

   $scope.canBeSaved();
}]);