【问题标题】:Prepopulate AngularJS form with invalid data使用无效数据预填充 AngularJS 表单
【发布时间】:2014-01-17 04:18:29
【问题描述】:

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

小例子:

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

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

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

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

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

你可以通过创建一个指令来解决这个问题,直到这个错误被修复:)

我从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);
          }
        });
      }
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 2016-07-24
    • 2018-08-15
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多