Angularjs directive to auto add new row on key input in last row

For a multi-row input capture, we can either use a add new row button or automatically add new row as the user enters some text on the current row. the later is preferred as it saves user from extra clicks and makes the UI clean. Here we will see how to add a new row automatically using angularjs directive.


Every time we do an key input on the last row, a new row is added. Try the following demo and see for yourself.
{{rows | json}}



<!DOCTYPE html>

  <script src=""></script>
  <script src="script.js"></script>
    .demo-here {
      width: 230px;
      margin: auto;
      padding: 30px;
      border: 1px solid #ff9800;
      margin-bottom: 10px;
    .inputfield { width: 150px; }
    .delete-btn { width: 75px; }

  <div class="demo-here" ng-app="AddNewTest" ng-controller="AddNewController">
    <pre>{{rows | json}}</pre>
    <div class="items" ng-repeat="row in rows">
      <add-new-row data="rows" index="$index"></add-new-row>



angular.module('AddNewTest', []).
directive('addNewRow', function ($timeout) {
  return {
    controller: function ($scope) {
      $scope.deleteRow = function (index) {
        console.log('Delete row here');
        $scope.rows.splice(index, 1);
    link: function (scope, element, attribute) {
      element.on('keyup', function(event){
        if(scope.index + 1 == scope.rows.length) {
          var code = event.keyCode || event.which;
        // Skip adding row if key pressed is 'Tab', 'Shift' or 'Esc'
        if(!(code == 9 || code == 16 || code == 27)) {
          console.log('keyup happening');
          $timeout(function () {
            scope.rows.push({ value: '' });
    restrict: 'E',
    replace: true,
    scope: {
      index: '=',
      rows: '=data'
   template: '<div class="add-new"><input class="inputfield" type="text" placeholder="Row {{index + 1}}" ng-model="rows[index].value" /><button class="delete-btn" ng-click="deleteRow(index)">Delete</button>{{value}}</div>'
controller('AddNewController', function ($scope, $timeout) {
  $scope.rows = [
  { value: '' }
Follow me on twitter to stay upto date about the angular related blogs.