在AngularJS动态电子邮件验证元素中,当我填写电子邮件检查元素时,它已重置 [英] In the AngularJS Dynamic email validation element, When I fill out the email check element, It's reset

查看:342
本文介绍了在AngularJS动态电子邮件验证元素中,当我填写电子邮件检查元素时,它已重置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Angular.JS中的电子邮件检查元素代码几乎可以,但这有一个问题。
当我填写电子邮件检查元素时,它已重置!

This is Email Check Element Code in Angular.JS Almost is Ok, But this has a problem. When I fill out the email check element, It's reset!

示例
我将此写入电子邮件检查元素。

Example I Write this into email check element.

test@test.com

"test@test.com"

但这是重置!当我写'。'< - point。

But this is Reset! when i write the '.' <- point.

test @ test< - OK

"test@test" <- OK

测试@测试。 < - 重置输入。当我写'。'< -

"test@test." <- Reset the Input. When I write the '.' <-

为什么会出现问题?

Javascript

    <script>
angular.module('test', [])
    .controller('MyController', ['$scope', '$window', function($scope, $window) {
        $scope.sendMessage=function(toSb){
            alert(toSb);
        };

    }])
    .directive('emailInput', function($compile) {
        return {            
            restrict: 'C',          
            template: '<input type="email" ng-model="emailtext" required>{{emailtext}}',
            link: function(scope, elem, attrs){
                    scope.name="emailAddress";

                    var input = elem.find("input")[0];
                    input.name = "emailAddress";                                    
                    $compile(input)(scope);


            }
        };
    });
</script>

HTML

<form name="myForm">
<div class="email-input"></div>
inputIsValid={{myForm.emailAddress.$valid}}<br>
<span class="error" ng-show="myForm.emailAddress.$error.required">Required!</span>
<span class="error" ng-show="myForm.emailAddress.$error.email">Not valid email!</span>
</form>


推荐答案

您需要使用replace选项生成指令从指令元素中获取name属性(基本上不再编译输入)。当您编译指令时,角度验证显示奇怪的行为,它在解析后重置modelValue(未定义),但在某种程度上,它也会重置viewvalue。您可以看到,如果您直接使用输入类型,则不会发生这种情况,似乎重新编译模板会导致此问题

You would need to make your directive with replace option and get the name attribute from the directive element (Basically do not compile the input again). It is the angular validation showing weird behavior when you have your directive compiled, it resets the modelValue (undefined) after parsing but somehow in this case, it resets the viewvalue as well. You can see that it does not happen if you use the input type directly, It seems like the recompiling of the template is causing this issue.

.directive('emailInput', function ($compile) {
    return {
        restrict: 'C',
        replace:true,
        template: '<input type="email"  ng-model="emailtext" required>',
        link: function (scope, elem, attrs) {

        }
    };

<div class="email-input" name="emailAddress"></div>

Plnkr

Plnkr

这篇关于在AngularJS动态电子邮件验证元素中,当我填写电子邮件检查元素时,它已重置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆