我可以限制添加到数组中的项目数量吗?

Can I cap the amount of items I add to an array?

我的应用程序使用文本输入向数组中添加项目。我想说的是,一旦这个数组有 = 到 50 个项目,然后禁用搜索输入。我使用 "clear completed" 按钮来清除已勾选的任务(项目)。因此,重新启用输入的唯一方法是清除一些项目。

我正在使用 Angular.JS,我假设我需要一个 for 循环来说明一些事情,如果项目 = 50,则禁用文本输入,否则启用输入。

我就是不知道怎么写...

Angular数组

 $scope.todos = [
    {text:'Build this ToDo List', done:true},         
    {text: 'Test this ToDo list', done:false}
    //tasks added through text input...
  ];
应用的

HTML:

<div class="todo-wrapper" ng-controller="TodoCtrl">
      <form>
        <input class="add-input" placeholder="Add a new task..." type="text" ng-model="formTodoText" ng-model-instant/>
        <button class="add-btn" ng-click="addTodo()"><h2>+</h2></button>
      </form>
      <div class="max-window">
        <ul>
          <li class="tasks" ng-repeat="todo in todos">
            <label class="label--checkbox">
              <input class="checks" type="checkbox" ng-model="todo.done" checked/>
              <span class="done-{{todo.done}}">{{todo.text}}</span>
            </label>
          </li>
        </ul>
      </div>
      <button class="clear-btn" ng-click="clearCompleted()">Clear completed</button>
    </div>

Angular 函数

将项目添加到数组

$scope.addTodo = function () {
    $scope.todos.push({text:$scope.formTodoText, done:false});
    $scope.formTodoText = '';
  };

从数组中清除已完成的任务(项目)

$scope.clearCompleted = function () {
        $scope.todos = _.filter($scope.todos, function(todo){
            return !todo.done;
        });

If/Else 声明 ?

if ($scope.todos = 50) {
    document.getElementsByClassName('add-input').disabled = true;
    document.getElementsByClassName('add-btn').disabled = true;
} else {
    document.getElementsByClassName('add-input').disabled = false;
    document.getElementsByClassName('add-btn').disabled = false;
}

或者,如果我可以禁用 add-btnenter to submit 这也可以解决我的问题。这可能吗?

感谢您的帮助!

编辑

问题已通过使用 ng-disabled

解决

输入

<input class="add-input" placeholder="Add a new task..." type="text" ng-model="formTodoText" ng-model-instant ng-disabled="todos.length >= 4"/>

按钮

<button class="add-btn" ng-click="addTodo()"ng-disabled="todos.length >= 4"><h2>+</h2></button>

您可以使用 length 属性 数组。

The length property represents an unsigned, 32-bit integer that specifies the number of elements in an array

代码

if($scope.todos.length == 50)

你也可以使用ngDisabled指令

This directive sets the disabled attribute on the element if the expression inside ngDisabled evaluates to truthy.

<button ng-disabled="todos.length == 50" ng-click="addTodo()"><h2>+</h2></button>

在您的输入中添加 ng-disabled 指令:

<input class="add-input" placeholder="Add a new task..." type="text" ng-model="formTodoText" ng-model-instant ng-disabled="todos.length >= 50"/>

ng-disabled 中的表达式是一个布尔值,为真时禁用输入,为假时启用。