「カスタム フィールド」オブジェクトに基づいて<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);
}
}
};
}])
fiddleも参照してください。