Angular - 仅当数组中的对象包含 completed:true 时才启用按钮

Angular - Enable button only if object inside an array contains completed:true

我有一个包含一堆对象的数组。如果没有对象包含键 "completed" 的 "true" 值,我想禁用一个按钮。

//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>

感谢任何帮助。

您可以在 todos 对象上放置过滤器并检查其长度。

标记

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

Working Fiddle

你可以检查类似

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>

你可以试试:

html:

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

在控制器中:

$scope.isDisabled = function () {
        var disabled = true;
        angular.forEach($scope.todos, function(todo){
            if(todo.completed === true){
                disabled = false;
            }
        });
        return disabled;
    };
ng-disabled="(todos | filter: {completed:true}).length < 1"