我想知道是否可以在 html 模板中检索当前表单。
明确地说,我实际上想以这种方式重用一些表单字段:
<form name="myForm">
<div ng-include src="'templates/form-field/email.html'">
<div ng-include src="'templates/form-field/password.html'">
</form>
这里是 templates/form-field/email.html:
<div>
<label>Email:</label>
<input type="email" name="email" ng-model="data.email" ng-required="true">
</div>
<div ng-show="myForm.email.$error.required && myForm.email.$touched" class="error">Email is required</div>
<div ng-show="myForm.email.$error.email && myForm.email.$touched" class="error">Email is not valid</div>
所以这很好用,并允许我重新使用 HTML 组件,包括错误消息。 但是,我必须为我的表单提供一个静态名称(此处为“MyForm”)
有什么方法可以检索标签内的当前表单吗?
我对 angular 还很陌生,所以甚至可能有更好的方法来实现我不知道的相同行为(即重用 html 组件/错误消息)。
我对任何解决方案都感兴趣,只要它不包含任何第 3 方。
也许使用 $scope 来定义表单的名称?
最佳答案
使用 ng-include
它从父级创建一个子级作用域,因此数据仅在父级到子级之间单向共享。您将需要创建一个指令,并将 scope
设置为 false
,或者根本不声明它,因为这是默认设置,这样 Controller 和指令将共享相同的范围。
电子邮件指令:
directive('emailTemplate', [function(){
return {
templateUrl: 'templates/form-field/email.html',
link: function(scope, elem, attrs) {
}
};
}]);
密码指令:
directive('passwordTemplate', [function(){
return {
templateUrl: 'templates/form-field/password.html',
link: function(scope, elem, attrs) {
}
};
}]);
HTML
<form name="myForm">
<email-template></email-template>
<password-template></password-template>
</form>
编辑
电子邮件指令:
directive('emailTemplate', [function(){
return {
templateUrl: 'templates/form-field/email.html',
link: function(scope, elem, attrs) {
scope.form = scope[attrs.formName];
}
};
}]);
HTML
<form name="myForm">
<email-template form-name="myForm"></email-template>
<password-template form-name="myForm"></password-template>
</form>
模板
<div>
<label>Email:</label>
<input type="email" name="email" ng-model="data.email" ng-required="true">
</div>
<div ng-show="form.email.$error.required && form.email.$touched" class="error">Email is required</div>
<div ng-show="form.email.$error.email && form.email.$touched" class="error">Email is not valid</div>
关于javascript - Angular 在 html 中获取当前表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32237215/