Seb*_*erg 19 javascript web-component angularjs
我正在将我的遗留代码库移植到使用AngularJS 1.5推广的新组件架构.我在为更大的表单执行此操作时遇到了问题.传统上,我会附加表单验证如下:
<form name="myForm">
<input type="text" name="input1" ng-model="vm.input1" required />
<div ng-messages="myForm.input1.$error">
<div ng-message="required">Please fill out this field.</div>
</div>
<!-- many more inputs -->
</form>
Run Code Online (Sandbox Code Playgroud)
转换到组件体系结构时,我必须将表单显式传递给组件:
<form name="vm.myForm">
<my-awesome-input-component model="vm.input1" form="vm.myForm"><my-awesome-input-component>
<!-- many more inputs -->
</form>
Run Code Online (Sandbox Code Playgroud)
我想避免vm用我的表格污染.有没有更好的方法来实现表单所需的组件架构?
RGo*_*lez 22
更新 - 将表单名称更改为表单引用,因为我们没有明确表示我们传递的是实际的表单引用,而不仅仅是表单的名称.这可以随心所欲地调用,只要清楚它实际上是什么.
正如Iain Reid的评论所说,你不需要使用vm.您只需将表单命名为您想要的任何名称,然后将该名称传递给您的组件,因此它看起来像这样:
<form name="myForm" ng-submit="ctrl.someFunction()" novalidate>
<my-input form-reference="myForm"></my-input>
<button type="submit">Some button</button>
</form>
Run Code Online (Sandbox Code Playgroud)
如果您想自己处理验证(通过使用我认为您使用的ng-messages),请确保在表单中写入"novalidate"以禁用默认浏览器验证.
然后从那里,在我的组件上,我会写一些类似于:
angular.module("myApp")
.component("myInput",{
templateUrl:'path/to/template.html'
bindings:{
formReference:'<',
myInputModel:'<',
onUpdate:'&'
},
controller: MyInputController
}
Run Code Online (Sandbox Code Playgroud)
然后在输入模板中:
<input type="text" name="myInput" ng-model="$ctrl.myInputModel" ng-change="$ctrl.update($ctrl.myInputModel)" required />
<div ng-messages="$ctrl.formReference.myInput.$error">
<div ng-message="required">Please fill out this field.</div>
</div>
Run Code Online (Sandbox Code Playgroud)
关于绑定以及如何传递和更新模型的一些额外说明:
所以在输入控制器中我会写一些类似于:
function MyInputController(){
var ctrl = this;
ctrl.update = function(value){
ctrl.onUpdate({value: value});
};
}
Run Code Online (Sandbox Code Playgroud)
最后,当我在表单中使用我的组件时:
<form name="myForm" ng-submit="ctrl.someFunction()" novalidate>
<my-input form-reference="myForm" my-input-model="ctrl.anyModelIWant" on-update="ctrl.updateMyInput(value)"></my-input>
<button type="submit">Some button</button>
</form>
Run Code Online (Sandbox Code Playgroud)
并且表单的控制器将具有以下功能:
...
ctrl.updateMyInput = function(value){
ctrl.anyModelIWant = value;
}
...
Run Code Online (Sandbox Code Playgroud)
官方文档:https://docs.angularjs.org/guide/component
我希望所有这些都可以帮助那些人:-)