6

I got an input directive that should allow users to undo.

Enter saves the value using some function, Esc Cancel edits from the last save.

For the Esc keypress event i'm using ngmodel.$setViewValue(scope.last_saved_value) but the input is not updating. I know from the docs that this function does not trigger $digest so i put it in an $apply but it is still not working.

JSBIN example

haki
  • 9,389
  • 15
  • 62
  • 110

2 Answers2

39

Try calling ngmodel.$render(); after you do $setViewValue, it should help.

scniro
  • 16,844
  • 8
  • 62
  • 106
Ivan Koshelev
  • 3,830
  • 2
  • 30
  • 50
  • I thought the `$render` method should be implemented by the developer, but I guess that only applies for custom controls. Calling it for inputs (`type="checkbox"` and `type="text"` in my case) works perfectly. Thanks. – Carlos Garcia Apr 13 '16 at 00:29
2

I usually both include and require the ngModel:

app.directive('cancelableInput', function($timeout) { 
  return { 
    restrict : "A",
    require : 'ngModel', 
    scope: {
      ngModel: '=?'
    },

Then, when you want to change the model value and have it update, you can just do:

scope.$apply(function() {
  scope.ngModel = scope.last_saved_value;
});
dave
  • 62,300
  • 5
  • 72
  • 93
  • Hey @dave. I guess the key here is the two way binding ? i mean, i was probably (though it really makes no sense) updating a local copy of the ng-model ? – haki Apr 05 '14 at 08:12