在AngularJS动态电子邮件验证元素中,当我填写电子邮件检查元素时,它's重置

In the AngularJS Dynamic email validation element, When I fill out the email check element, It's reset

本文关键字:电子邮件 元素 重置 检查 验证 动态 AngularJS      更新时间:2023-09-26

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

示例我把这个写进电子邮件检查元素。

"test@test.com"

但这是重置!当我写"。"<-指向

"test@test"<-正常

"test@test."<-重置输入。当我写入'.'<-时

为什么会出现问题?

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。您可以看到,如果您直接使用输入类型,就不会发生这种情况,似乎是重新编译模板导致了这个问题

.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