问题
因为项目需求,页面中的表单字段为异步生成,所以我封装了一个组件来生成表单,但是推测可能是因为异步生成的原因,无论如果 angular 中 form 都一直是 valid 状态,进行 submit 操作只能触发原生的 invalid 事件
关键代码
<script type="text/ng-template" id="text.tpl">
<md-input-container>
<label ng-bind="label"></label>
<input ng-attr-name="{{name}}" ng-model="myModel" ng-required="required">
</md-input-container>
</script>
<script type="text/ng-template" id="select.tpl">
// ...
</script>
<!-- 上方定义一些可能出现的组件 如 input select 等 -->
<form name="form" layout="column">
<my-form-item
ng-repeat="item in data.form"
type="item.type"
label="item.label"
my-model="$parent.myForm[item.name]"
ng-attr-name="item.name"
options="item.options"
required="item.required"></my-form-item>
<md-button type="submit" class="md-raised md-primary" ng-disabled="form.$invalid">提交</md-button>
</form>
myApp.directive('myFormItem', function($compile, $templateCache) {
return {
scope: {
type: '=',
label: '=',
name: '=',
required: '=',
options: '=',
myModel: '='
},
link: function(scope, element, attrs) {
scope.$watch('type', function(type) {
if (type) {
element.replaceWith($compile($templateCache.get(type + '.tpl'))(scope))
}
})
}
}
})
form指令好像只对静态的具有name属性的表单元素有效果,这种动态拼接的模板似乎木有作用。
不过可以试试
ngForm
这个东西,大体的作用就是可以在form里面再嵌套一个form,它在官方文档也说了,是为了对表单项进行分组的,虽然这里用不到分组的功能,但是可以解决form对于静态name属性的依赖问题。原来我做过一个项目中的表单生成逻辑是使用ng-repeat来做,我觉的应该和你这里的意思是差不多的吧。