How to output text from html input to AngularJS array?

I'm new to AngularJS - trying to create a beautiful vanilla todo-list app. I can't figure out how to output the text value from the input field to the "todos" array.

Here is my code.

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 = []
  }


});

      

Thanks in advance!

+3


source to share


3 answers


I guess this is just a typo in your template, try

{{todo}}

      

instead

{{todo}

      



Everything else looks fine

Completed code here: http://plnkr.co/edit/tRGw9UTRVhXvD51lxYjF?p=preview

I also added a track using the $ index operator to allow duplicate todos.

+1


source


You are not using the "plunker" module. You must use ng-app to include the module. \

Updated and working code

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 = []
 }
});

      

Hope it helps!

+1


source


maybe you can write this just to debug it big

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

      

in your template, call

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

      

one way to help yourself:

  • use many consoles, everyone is a beginner, just use them until you understand the workflow.

  • use local variable, global variable is always confusing even for Pro.

0


source







All Articles