javascript - Angular 在 html 中获取当前表单

标签 javascript html angularjs

我想知道是否可以在 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/

相关文章:

javascript - 想要在 Angular JS 中将多个 json 对象转换为数组

Javascript:从自定义 API 将许多图像加载到 DOM 中,无需使用 base64-dataURLs

javascript - AngularJS ng-repeat 用于动态子 json 数组

javascript - VS Code 向我在 JavaScript 和 TypeScript 中的函数调用添加了奇怪的文本

javascript - 避免模​​糊事件的完美方法

html - 如何防止网页缩放

angularjs - Angular ui-router ng-if当前确切状态

javascript - AngularJS:使用 ui-select 时如何选择对象字段?

javascript - Vue.js 是否有内置方法将持久对象的副本添加到重复数组

javascript - 根据符号拆分字符串