1

I want to make a list of items, double-clicking on one item makes it editable. Currently, while editing an item, clicking outside (ie, blur) submits the new value. But, I also want enter on the keyboard to be able to submit the change.

Now, ng-keyup, ng-keydown, ng-keypress are part of AngularJS. I am thinking of using them. Here is my current code. It can catch the event of enter and the item that we are editing, but I don't know how to do the rest.

Could anyone help?

    var app = angular.module('app', []);
    app.controller('Ctrl', ['$scope', function ($scope) {
      $scope.items = [{ name: "item #1" }, { name: "item #2" }, { name: "item #3" }];
      $scope.eEditable = -1;
      $scope.up = function ($event, item) {
        if ($event.keyCode === 13) {
          console.log(item.name);
          // what to do?
        }
      }
    }])
    input {
      font-size: 20px;
      border:none;
      background-color:transparent;
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<body ng-app="app" ng-controller="Ctrl">
  <table>
    <tr ng-repeat="item in items">
      <td>
        <input type="text" value="{{item.name}}" ng-blur='eEditable = -1' ng-readonly='$index !== eEditable' ng-dblclick="eEditable = $index" ng-keyup="up($event, item)"/>
      </td>
    </tr>
  </table>
</body>

PS: JSBin

SoftTimur
  • 5,630
  • 38
  • 140
  • 292

2 Answers2

0

just set eEditable back to -1

$scope.up = function ($event, item) {
    if ($event.keyCode === 13) {
      console.log(item.name);
      $scope.eEditable = -1;
    }
  }
Chinito
  • 1,085
  • 1
  • 9
  • 11
  • just do it like the ng-blur – Chinito Mar 21 '17 at 09:43
  • It will not work of course. child scope shadowing :) You could mess with $parent scope of dot referencing (don't know how to put it better). Simpler to trigger blur event on event.target. Or use controllerAs. – dfsq Mar 21 '17 at 09:47
  • i didn't say you have to trigger the ng-blur. my point is that you just have to copy like what you did with the ng-blur. – Chinito Mar 21 '17 at 09:59
0
var app = angular.module('app', []);
app.controller('Ctrl', ['$scope', function ($scope) {
  $scope.items = [{ name: "item #1" }, { name: "item #2" }, { name: "item #3" }];
  $scope.eEditable = -1;
  $scope.up = function ($event, item) {
    if ($event.keyCode === 13) {
        $event.currentTarget.blur();
    }
  }
}])
bluehipy
  • 2,254
  • 1
  • 13
  • 19