gpt4 book ai didi

javascript - AngularJS 表单验证 - formName.$valid 始终为真

转载 作者:行者123 更新时间:2023-11-30 00:02:48 25 4
gpt4 key购买 nike

我有一个简单的表单,其中的字段是通过名为 field 的指令动态生成的。当我点击提交时,字段被验证并生成一个有效的类名,例如 ng-invalidng-invalid-email。但是表单的类名总是ng-valid。任何帮助将不胜感激!

Plnkr

HTML

<body ng-controller="app_controller">
<form name="register" ng-submit="register_user()" novalidate>
<table>
<tr>
<td>Username: </td>
<td><field name="username" value="info"></field></td>
</tr>
<tr>
<td>Email: </td>
<td><field name="email" value="info"></field></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" ng-disabled="register.$invalid" /></td>
</tr>
</table>

Invalid: {{ register.$invalid }} <br />
valid: {{ register.$valid }}
</form>

JS

var app = angular.module('app', []);

app.controller('app_controller', function($rootScope, $scope) {
$scope.info = {
username: '',
email: ''
};

$rootScope.meta = {
"username": {
type: "STRING",
length: 255
},
"email": {
type: "EMAIL",
length: 255
}
};
});

app.directive('field', function($rootScope, $compile) {
return {
restrict: 'E',
scope: {
value: '='
},
link: function($scope, $element, $attrs) {
$scope.field_name = $attrs.name;
$scope.required = true;
console.log($scope);
var prepare_fields = function() {
if ($rootScope.meta) {
$scope.field = angular.copy($rootScope.meta[$attrs.name]);
}

var html = '';
if ($scope.field.type === "STRING") {
html = '<input type="text" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />';
} else if ($scope.field.type === "EMAIL") {
html = '<input type="email" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />';
}

$element.html($compile(html)($scope));
};

$rootScope.$watch('meta', prepare_fields);
}
}
});

最佳答案

在添加内容后编译element.contents 所以只需添加以下两行

$element.html(html);
$compile($element.contents())($scope);

代替

$element.html($compile(html)($scope));

应该可以了:)

指令中的最终代码:

var html = '';
if ($scope.field.type === "STRING") {
html = '<input type="text" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />';
} else if ($scope.field.type === "EMAIL") {
html = '<input type="email" name="' +$scope.field_name+ '" ng-model="value[field_name]" ng-required="required" />';
}

// $element.html($compile(html)($scope));
$element.html(html);
$compile($element.contents())($scope);

N.B:问题是您编译的是字符串而不是元素 html。所以在修改 element 之后编译 element contents 然后它就可以工作了。

关于javascript - AngularJS 表单验证 - formName.$valid 始终为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39699323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com