【发布时间】:2015-10-22 00:33:15
【问题描述】:
我正在动态地在表单中创建输入。我为此目的创建了这个指令:
// Generate inputs on the fly using BE data.
.directive('inputGenerator', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
id: '@',
type: '@',
name: '@',
attributes: '=',
ngModel: '=',
ngDisabled: '='
},
link: function (scope, iElement, iAttrs) {
// Get attributes
var id = iAttrs.id,
type = iAttrs.type,
name = iAttrs.name;
scope.ngModel[name] = {};
var extended_attributes = {
"type": type,
"id": id,
"data-ng-model": 'ngModel.' + name + '[\'value\']',
"name": name,
"data-ng-disabled": "ngDisabled"
};
if ( ! scope.attributes) {
scope.attributes = {};
}
// Append extra attributes to the object
angular.extend(scope.attributes, extended_attributes);
// Generate input
var input = '<input ';
angular.forEach(scope.attributes, function (value, key) {
input += key + '="' + value + '" ';
});
input += '/>';
// Compile input element using current scope (directive) variables
var compiledElement = $compile(input)(scope);
// Set the file selected name as the model value
compiledElement.on('change', function () {
if (this.files && this.files[0].name) {
var that = this;
scope.$apply(function () {
scope.ngModel[name] = {};
scope.ngModel[name]['value'] = that.files[0].name;
});
}
});
// Replace directive element with generated input
iElement.replaceWith(compiledElement);
}
};
}]);
此 html 行将触发指令:
<input-generator data-name="{{ item.name }}" data-ng-model="inputs.sources" data-attributes="item.attrs" data-type="{{ item.type }}" data-id="inputFile_{{ $index }}" data-ng-disabled="inputs.sources[item.name].selected" />
我在 Angular 1.4.3 上运行。
问题
模型和几乎所有指令在指令中都可以正常工作,但由于某种原因,当添加的输入无效时,表单仍然有效,正如您在这张图片中看到的那样。
我已经试过了:
表单验证的任何 Angular 功能都有效
我调试了 Angular,似乎是附加到表单的输入与指令内编译的输入不同。
我已经在每个输入创建后调用了formName.$setPristine(),但它不起作用。
我无法通过指令访问表单,但我认为这也不是一个好主意。
我已经用 ng-form 标签包装了输入,但没有任何用处。
我尝试使用指令编译方法,但这只是在应用加载时触发一次,并且我有一个选择输入,可以在更改时加载不同的输入。
非常感谢您对此的任何帮助! :)
感谢大家的贡献!!
【问题讨论】:
标签: javascript angularjs forms validation directive