我有2个指令,一个是my-form,一个是my-field。
除了输入字段的ngModelController之外,一切都运行良好
所以我无法获得这些字段的$ dirty,$ valid属性
例如,在提交时,我想获取名为“field1”的输入的ngModelController,但我无法得到它。
form.field1未定义。
在FormController“form1”中,没有字段,任何人都可以帮忙吗?
非常感谢
小提琴中的代码如下:
https://jsfiddle.net/luneyq/0td5hLur/2/
主要代码也列在下面:
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.config = {
name: 'form1',
fields: [
{type: 'text', name: 'field1', model: 'obj.field1'},
{type: 'text', name: 'field2', model: 'obj.field2'}
]
};
}])
.directive('myForm', function() {
return {
restrict: 'E',
replace: true,
template: '' +
'<form name="{{config.name}}">' +
' <my-field ng-repeat="item in config.fields" config="item"></my-field>' +
' <button ng-click="submit()">submit</button>' +
'</form>',
scope: {
config: '='
},
link: function(scope, el, attr) {
scope.obj = {};
scope.submit = function() {
var form = scope[scope.config.name];
alert(form.field1);
alert(form.field1.$dirty); // error here
}
}
}
})
.directive('myField', ['$compile', function($compile) {
return {
restrict: 'E',
replace: true,
link: function(scope, iElement, iAttrs) {
scope.config = scope.$eval(iAttrs.config);
var config = scope.config;
var html = '<input type="' + config.type + '" ng-model="' + config.model + '" name="' + config.name + '" />';
iElement.after($compile(html)(scope));
iElement.remove();
}
}
}])
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<my-form config="config"></my-form>
</div>
答案 0 :(得分:1)
试试这个:
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.config = {
name: 'form1',
fields: [
{type: 'text', name: 'field1', model: ''},
{type: 'text', name: 'field2', model: ''}
]
};
}])
.directive('myForm', function() {
return {
restrict: 'E',
replace: true,
template: '' +
'<form name="{{config.name}}">' +
' <my-field ng-repeat="item in config.fields" field="item"></my-field>' +
' <button ng-click="submit()">submit</button>' +
'</form>',
scope: {
config: '='
},
link: function(scope, el, attr) {
scope.submit = function() {
var form = scope[scope.config.name];
angular.forEach(scope.config.fields, function(item){
console.log(item.name + ": " + form[item.name].$dirty);
});
}
}
}
})
.directive('myField', function() {
return {
restrict: 'E',
replace: true,
template: '' +
'<input type="{{field.type}}" ng-model="field.model" name=" {{field.name}}" />',
scope: {
field: '='
}
}
})
;
答案 1 :(得分:0)
我自己试了一下,只修改了几行,但这真的不是一件容易的事
请参考另一篇文章:
angularjs custom form and field directive: ngModelController is not found in FormController enter link description here