问题
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"
But this is Reset! when i write the '.' <- point.
"test@test" <- OK
"test@test." <- Reset the Input. When I write the '.' <-
Why the problem occured?
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>
回答1:
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) {
}
};
and
<div class="email-input" name="emailAddress"></div>
Plnkr
来源:https://stackoverflow.com/questions/25578469/in-the-angularjs-dynamic-email-validation-element-when-i-fill-out-the-email-che