1

I have an array that contains a bunch of objects. If there are no objects that contains a "true" value for the key "completed", I would like to disable a button.

//Here is the format for the array of objects:

$scope.todos = [{
                task:$scope.task,
                completed: false,
                localID:Date.now(),
                display: true
}];

//Here is the button I want to disable::

<button ng-click="clear()" class="btn" ng-disabled="">Clear Completed</button>

Any help is appreciated.

georgeawg
  • 48,608
  • 13
  • 72
  • 95

4 Answers4

4

You could place filter over your todos object and check for there length.

Markup

<button ng-click="clear()" class="btn" ng-disabled="(todos | filter: {completed:true}).length < 1">
     Clear Completed
</button>

Working Fiddle

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
3

You can check something like

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.todos = [{
    task: $scope.task,
    completed: false,
    localID: Date.now(),
    display: true
  }];

  $scope.isDisabled = function() {
    return $scope.todos.some(function(item) {
      return item.display === true
    })
  }


})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
  <input type="checkbox" ng-model="todos[0].display" <br />
  <button ng-click="clear()" class="btn" ng-disabled="isDisabled()">Clear Completed</button>
</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1
ng-disabled="(todos | filter: {completed:true}).length < 1"
0

you can try:

html:

<button ng-click="clear()" class="btn" ng-disabled="isDisabled()">Clear Completed</button>

in controller:

$scope.isDisabled = function () {
        var disabled = true;
        angular.forEach($scope.todos, function(todo){
            if(todo.completed === true){
                disabled = false;
            }
        });
        return disabled;
    };
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68