0

I couldn't find anything useful to resolve my problem, so hopefully I could get an answer here.

Below is a simplified snippet.

What I'm trying to achieve is that on the input field blur the new value of C is saved to DB. Also when X is clicked the field is emptied and nothing is saved. The problem is that when user types something in the input field and then changes his/her mind and empties it, the ng-blur triggers (which is logical because it's off the element) and the new entered value is saved to db before the field is emptied. If I remove the blur event from input field and place it for the whole the "X" button works like it should, but blur event never fires.

I can't add any more extra elements into the table anymore, so have to solve this issues somehow.

angular.module("App", [])
.controller("Ctrl", function(){
  
    this.items = [
        {A: "111", B: "222", C: "333"},
        {A: "111", B: "222", C: "333"},
        {A: "111", B: "222", C: "333"},
        {A: "111", B: "222", C: "333"},
        {A: "111", B: "222", C: "333"}
        ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App">
    <div ng-controller="Ctrl as ctrl">
        <table ng-repeat="item in ctrl.items">
          <tbody>
            <tr>
                <td>{{item.A}}</td>
                <td>{{item.C || item.B}}</td>
                <td><a ng-click="showInput = !showInput"> edit</a> </td>                
            </tr>
          <tr ng-hide="!showInput">
            <td><input ng-blur="showInput = false" type="text" ng-model="item.C" placeholder="Your name for item A"/></td>
              <td><a ng-click="item.C = null">X</a></td>
          </tr>
            </tbody>
        </table>
    </div>
</div>

I'm still in the process of learning angular, so I'm sorry if I'm missing something. Any advice is much appreciated.

Edits:

  • I've forgotten to mention in my app the input field disappears after it saves the value. So no events of "X" trigger.

  • I moved ng-blur to input field to get the attention on my exact problem. This doesn't work: in case user changes his/her mind (doesn't want to save new value at all) and clicks "X", ng-blur still triggers and the value is saved. It shouldn't be.

  • Edited snippet to be more obvious.

AmeRyoki
  • 376
  • 1
  • 3
  • 14

0 Answers0