这是我正在使用的指令中的处理方式——注意链接函数底部的编译。在您的情况下,您可能需要一个仅针对该类型的指令 - 这样您就可以继续使用现有代码 - 类似于 field-type="{{input.fieldType}}",然后只需使用 element.find("input").attr("type", attrs.fieldType),然后进行编译。
angular.module("schemaForm").directive("schemaFormField",
['$compile', '$templateCache', '$dialog', '$q',
function ($compile, $templateCache, $dialog, $q) {
return {
restrict: "EA",
replace: true,
require: "^form",
scope: {
schema: "=",
model: "=",
field: "=",
required: "=",
onClick: "@",
editAs: "@"
},
link: function (scope, element, attrs, formController) {
var template;
var searchBox = $templateCache.get("searchBox.html");
scope.formState = formController; // form state checking (pristine, etc.)
scope.opts = {
backdrop: true,
keyboard: true,
backdropClick: true,
template: searchBox,
//templateUrl: 'schemaFormSearchBox.html',
controller: 'schemaFormSearchCtrl'
};
// enables ng-show of label
scope.isEmpty = function() {
return typeof scope.model[scope.field] === 'undefined';
};
// launches search dialog on ng-click
scope.search = function() {
scope.opts.item = scope.schema;
var d = $dialog.dialog(scope.opts);
d.open().then(function (result) {
if (result) { // don't overwrite if cancelled
scope.model[scope.field] = result;
}
});
};
// perhaps throw exeception instead?
if (scope.schema === undefined) {
return $compile(element.contents())(scope);
}
// assigned template according to form field type
template = (scope.schema["enum"] !== undefined) &&
(scope.schema["enum"] !== null) ?
$templateCache.get("enumField.html") :
$templateCache.get("" + scope.schema.type + "Field.html");
element.html(template);
// update attributes - type, ng-required, ng-pattern, name
if (scope.schema.type === "number" || scope.schema.type === "integer") {
element.find("input").attr("type", "number");
}
element.find("input").attr("ng-required", scope.required);
if (scope.schema.pattern) {
element.find("input").attr("ng-pattern", "/" + scope.schema.pattern + "/");
}
element.find("input").attr("name", scope.field);
// compile template against current scope
return $compile(element.contents())(scope);
}
};
}]);
})