Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 731
user3315570 Avatar asked Mar 17 '26 20:03

user3315570


2 Answers

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.

like image 69
Andrey Avatar answered Mar 20 '26 09:03

Andrey


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

like image 34
Satpal Tanan Avatar answered Mar 20 '26 08:03

Satpal Tanan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!