AngularJS自定义输入字段指令验证

时间:2013-09-09 16:15:10

标签: validation angularjs

我正在编写一个自定义字段指令,该指令根据“自定义字段”对象动态创建<input>字段(或<select><textarea>等)。我只希望指令包含表单字段,而不是任何验证或标签标记。这一直很好,直到验证。

在$编译时,看起来输入字段没有添加到父作用域的表单中。有没有办法手动添加它?我尝试FormController.$addControl()doc),这导致表单开始侦听输入模型上的更改,但表单状态(脏,有效等)仍未更新。

标记:

<div ng-controller="FieldController">
  <form name="customFieldForm">
    <label class="control-label" for="{{ field.name }}">{{ field.name }}:</label>
    <input-custom-field model="field"></input-custom-field>
    <span class="input-error" ng-show="customFieldForm.field.$error.required">
        Required</span>
  </form>
</div>

控制器:

myApp.controller("FieldController", function ($scope) {
  $scope.field =  {
    name: "Pressure in",
    required: true,
    readOnly: false,
    type: "decimal",
    value: null
  };
})

指令(删节):

.directive('inputCustomField', ['$compile', function ($compile) {
  var buildInput = function (field, ignoreRequired) {
    var html = '';
    var bindHtml = 'name="field" ng-model="field.value"';
    if (!ignoreRequired && field.required) {
        bindHtml += ' required';
    }
    switch (field.type) {
        case "integer":
            html += '<input type="number" ' + bindHtml + ' ng-pattern="/^\\d*$/">';
            break;
        case "decimal":
            html += '<input type="number" ' + bindHtml + ' class="no-spinner">';
            break;
    }
    return html;
  };

  return {
    restrict: 'E',
    require: '^form',
    scope: {
        field: "=model"
    },
    link: function (scope, elm, attrs, formController) {
        var fieldModel;
        var replacedEl;
        var renderInput = function (html) {
            replacedEl = $compile(html)(scope);
            elm.replaceWith(replacedEl);
            fieldModel = replacedEl.controller('ngModel');
            if (!fieldModel) fieldModel = replacedEl.find("input").controller('ngModel');
        };

        if (scope.field && scope.field.type) {
            var html = buildInput(scope.field, attrs.hasOwnProperty("ignoreRequired"));
            renderInput(html);
        }
    }
  };
}])

另见fiddle

0 个答案:

没有答案
相关问题