【问题标题】:How to push text from html input into AngularJS array?如何将文本从 html 输入推送到 AngularJS 数组中?
【发布时间】:2015-06-02 13:55:46
【问题描述】:

我是 AngularJS 的新手 - 尝试构建一个漂亮的普通待办事项列表应用程序。 我不知道如何将输入框中的文本值推送到 'todos' 数组中。

这是我的代码。

HTML:

  <body ng-controller="MainCtrl">
    <div class="container">
      <div class="main">
        <p>Todo App</p>
        <input ng-model="todoList" type="text" name="input" placeholder="Enter tasks here">
        <button ng-click="addTodo()">Add</button>
        <ul>
          <li ng-repeat="todo in todos">
            {{todo}
          </li>
        </ul>
      </div>
    </div>
  </body>

JS:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.todos = []
  $scope.todoList = "";

  $scope.addTodo = function(){
    $scope.todos.push($scope.todoList)
  }

  $scope.clearAll = function(){
    $scope.todos = []
  }


});

提前致谢!

【问题讨论】:

  • 有什么问题?您的代码工作正常! - JSFiddle 只是 }{{ todo } 中丢失了

标签: javascript arrays angularjs forms input


【解决方案1】:

我猜这只是你的模板中的一个错字,试试

{{todo}}

而不是

{{todo}

其他一切都很好

这里是完整的代码:http://plnkr.co/edit/tRGw9UTRVhXvD51lxYjF?p=preview

我还通过 $index 语句添加了跟踪以允许重复的待办事项。

【讨论】:

  • 干杯,不敢相信我错过了。有没有更好的方法来做我想做的事情?将输入元素包装在表单中是否是一个好习惯?
  • 在我看来 - 不。我认为,语义上的表单是与一个实体相关的多个输入的容器。当您想在没有 javascript 的情况下将某些内容发布/放入服务器时,也会使用表单。所以我认为没有必要将单个输入包装到表单中。
  • @user3315570 如果没有用,你为什么要把它包装在一个表单中?把事情简单化。我已经修改了 cmets 中的一个小提琴并将这一行添加到 ng-repeat:track by $index 因为从 Angular 1.2 及更高版本开始,它不允许在数组中重复,所以你必须使用索引来跟踪它。 jsfiddle.net/byw7kLuq/1
【解决方案2】:

您没有使用“plunker”模块。 您必须使用 ng-app 来包含该模块。\

更新和工作的代码是

HTML

<div class="container" data-ng-app="plunker" >
  <div class="main" data-ng-controller="MainCtrl">
    <p>Todo App</p>
    <input ng-model="todoList" type="text" name="input" placeholder="Enter tasks here">{{todoList}}
    <button ng-click="addTodo()">Add</button>
    <ul>
      <li ng-repeat="todo in todos">
        {{todo}}
      </li>
    </ul>
  </div>
</div>

JS

var app = angular.module('plunker',[]);
app.controller('MainCtrl', function($scope) {
$scope.todos = []
$scope.todoList = "";
$scope.addTodo = function(){
  $scope.todos.push($scope.todoList)
}
$scope.clearAll = function(){
  $scope.todos = []
 }
});

希望对你有帮助!!

【讨论】:

    【解决方案3】:

    也许你可以写这个只是为了调试它

    $scope.addTodo = function(todo) {
        // console.log(todo)
        $scope.todos.push(todo);
        // console.log($scope.todos)
    }
    

    在您的模板中,调用

    <input ng-model="todo" // (not todoList)
    <button ng-click="addTodo(todo)"> // (todo is local here)
    

    帮助自己的一种方法是执行以下操作

    1. 使用大量控制台,每个人都是一次新手,只需使用大量控制台,直到您了解工作流程为止

    2. 使用局部变量,全局变量总是令人困惑,即使是专业人士。

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 2017-03-29
      相关资源
      最近更新 更多