2

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

看起来输入字段在 $compiled 时没有添加到父范围的表单中。有没有办法手动添加?我尝试了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);
        }
    }
  };
}])

又见小提琴

4

0 回答 0