0

I am trying to append an element to the DOM from user text input using AngularJS. The desired behaviour is:

  • User types string into input ng-model "newTask"
  • Presses enter key
  • Dynamic element is then appended to the DOM

The relevant section of HTML is as follows:

<div class="add-task">
  <input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>

<div class="task-list">
  <a class="task"><span class="text">{{ newTask }}</span></a>
</div>
  • Currently the HTML is instantly updated. How can I bind this event to only happen after enter keypress? The AngularJS UI is also loaded.

Many appreciations, an AngularJS newbie

Barney
  • 1,820
  • 5
  • 29
  • 50

3 Answers3

1

Try creating a temp value

Html:

<input type="text" placeholder="Type then press enter to create task" ng-model="tmpTask" ng-keypress="saveTask($event)" />

Your ng-model binds to a tmpTask property. Only when enter is pressed, save it back to newTask

JS:

app.controller('MainCtrl', function($scope) {
  $scope.saveTask = function (event){
    if (event.keyCode == 13){
      $scope.newTask = $scope.tmpTask;
    }
  }
});

DEMO

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
1

html

<form ng-submit="createTask()">
    <input type="text" ng-model="newTaskText" />
</form>

<div ng-repeat="task in tasks">{{ task.text }}</div>

controller

$scope.tasks = [];

$scope.createTask = function() {
    $scope.tasks.push({
        text: $scope.newTaskText
    });
};
doodeec
  • 2,927
  • 19
  • 23
1

Since one of the other answers addresses the ng-keypress, I'll offer up the fact you don't need to use the ng-keypress event but can just watch the variable instead which negates the need for enter:

http://plnkr.co/edit/osFGRtpHG46bMyp15mc8?p=preview

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

 $scope.$watch('newTask', function(newVal){
     if (newVal=="newTask") {
       $scope.taskList.push("Task " + $scope.taskList.length);
       $scope.newTask = null;
     }
 });
});



 <body ng-controller="MainCtrl">
    <div class="add-task">
  <input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>

{{taskList.length}}
<div class="task-list" >
  <a class="task" ng-repeat="task in taskList" ><span class="text">{{ task }}&nbsp;</span></a>
</div>
  </body>
lucuma
  • 18,247
  • 4
  • 66
  • 91
  • This seems like the nicest method of achieving, but the Plunker you've linked to doesn't seem to work? – Barney Feb 06 '14 at 13:51
  • 1
    If you type in newTask (exactly) into the textbox it works. In general `$scope.$watch` runs everytime the variable changes so you can avoid the function on the keypress event. – lucuma Feb 06 '14 at 15:06