使用无效数据预填充AngularJS表单

the*_*met 5 javascript angularjs

我的模型包含一些未通过表单验证的数据(例如来自服务器的无效电子邮件地址).我仍然想向用户显示这个无效的模型数据,以便他们有机会修复它.

最小的例子:

  <form ng-init="email='foo'">
    <input type="email" ng-model="email"></input>
  </form>
Run Code Online (Sandbox Code Playgroud)

如何获取输入以显示初始无效模型值?

JS小提琴:http://jsfiddle.net/TwzXV/4/

all*_*kim 1

此行为被报告为错误。https://github.com/angular/angular.js/issues/2841

您可以通过创建指令来解决此问题,直到此错误得到修复:)

我从谷歌邮件列表中得到这个

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);
          }
        });
      }
    }
})
Run Code Online (Sandbox Code Playgroud)