Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepopulate AngularJS form with invalid data

My model contains some data that does not passes the form's validation (say an invalid email address that comes from the server). I still want to show this invalid model data to the user so they get a chance to fix it.

Minimal example:

  <form ng-init="email='foo'">
    <input type="email" ng-model="email"></input>
  </form>

How do I get the input to show the initial invalid model value?

JS Fiddle: http://jsfiddle.net/TwzXV/4/

like image 846
thesamet Avatar asked Nov 10 '22 14:11

thesamet


1 Answers

This behaviour is reported as a bug. https://github.com/angular/angular.js/issues/2841

You can go around this behaviour by creating a directive UNTIL this bug is fixed :)

I got this from google mailing list

http://jsfiddle.net/nalberg/XccGJ/

app.directive('displayInvalid', function($parse, $filter) {   
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, elm, attrs, model) {
        var displayed = false;
        scope.$watch(attrs.ngModel, function(newValue, oldValue, scope) {
          // only set once... on initial load
          if(displayed == false && oldValue != undefined){
            displayed = true;
            elm.val(model.$modelValue);
          }
        });
      }
    }
})
like image 109
allenhwkim Avatar answered Nov 15 '22 04:11

allenhwkim