Skip to content Skip to sidebar Skip to footer

Disable Button If Checkbox Is Unchecked In Angular JS

So I'm working on this web application. I have a list of categories, where if an item on the list is not checked, the 'Save'and 'Publish'buttons would be disabled. I understand ng-

Solution 1:

UPDATE: made the fiddle more like the actual scenario.

Wrap your <a> tag in a button and put the ng-dissabled on that.

Here's a jsfiddle that demonstrates how I would do this: 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();
}]);

Post a Comment for "Disable Button If Checkbox Is Unchecked In Angular JS"