user3315570
user3315570

Reputation: 101

How to push text from html input into AngularJS array?

I'm new to AngularJS - trying to build a pretty vanilla todo-list app. I can't figure out how to push the text value from the input box into the 'todos' array.

Here's 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!

Upvotes: 3

Views: 4284

Answers (3)

Satpal Tanan
Satpal Tanan

Reputation: 1108

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

The updated and working code is

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

Upvotes: 1

windmaomao
windmaomao

Reputation: 7680

maybe you can write this just to debug it a 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 is do the following

  1. use lot of console, everyone is newbie once, just use tons of them until you understand the workflow

  2. use local variable, global variable is always confusing, even to a Pro.

Upvotes: 0

Andrey
Andrey

Reputation: 4050

I guess it's just a typo in your template, try

{{todo}}

instead of

{{todo}

Everything else looks fine

Here is completed code: http://plnkr.co/edit/tRGw9UTRVhXvD51lxYjF?p=preview

I've also added track by $index statement to allow duplicated todos.

Upvotes: 1

Related Questions