gpt4 book ai didi

javascript - Angular 控制表单

转载 作者:行者123 更新时间:2023-12-03 11:24:16 24 4
gpt4 key购买 nike

所以我有这个表单片段:

<form name="registerForm" novalidate role="form">
<div class="row">
<div class="small-3 columns"><label for="pwd" class="right inline">Password:</label></div>
<div class="small-9 columns">
<label class="" ng-class="{'error': registerForm.pwd.$error.required && registerForm.pwd.$dirty}"><input type="password" id="pwd" name="pwd" ng-model="registerDetails.password" ng-required="true" /></label>
<small class="error" ng-show="registerForm.pwd.$error.required && registerForm.pwd.$dirty">Password Required</small>
</div>
</div>
</form>

正如您所看到的,有一个registerForm.pwd,它是表单名称加上输入名称。 Angular 已向此变量添加了诸如 $error$dirty 之类的内容。

有什么办法可以添加我自己的内容吗?就像通过指令 registerForm.pwd.$notEqual 一样?

最佳答案

是的,请参阅下面的 workink 演示。

var app = angular.module('app', []);
app.directive('validPasswordC', function() {
return {
require: 'ngModel',
scope: {

reference: '=validPasswordC'

},
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue, $scope) {
if (viewValue === "") {
ctrl.$setValidity('_required', false)
} else {
ctrl.$setValidity('_required', true)
}

var noMatch = viewValue != scope.reference
ctrl.$setValidity('notEqual', !noMatch)
});

scope.$watch("reference", function(value) {;
ctrl.$setValidity('notEqual', value === ctrl.$viewValue);

});
}
}
});
app.controller('homeCtrl', function($scope) {




});
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<div class="container" ng-app="app">
<form name="registerForm" novalidate role="form">
<div class="row">
<div class="small-3 columns">
<label for="pwd" class="right inline">Password:</label>
</div>
<div class="small-9 columns">
<label class="" ng-class="{'error': registerForm.pwd.$error.required && registerForm.pwd.$dirty}">
<input type="password" id="pwd" name="pwd" ng-model="registerDetails.password" placeholder=" password" ng-required="true" />



</label>
<label for="pwd" class="right inline">Confirm Password:</label>
<input type="password" id="password_c" name="pwdConfirm" ng-model="registerDetails.passwordConfirm" placeholder="confirm password" valid-password-c="registerDetails.password" ng-required="true" />

<p class="error" ng-show="registerForm.pwd.$error.required && registerForm.pwd.$dirty">
Password Required
</p>
<p ng-show="registerForm.pwdConfirm.$error.notEqual" class="error">
Passwords do not match.
</p>

<p class="error" ng-show="registerForm.pwdConfirm.$error.required && registerForm.pwdConfirm.$dirty || registerForm.pwdConfirm.$error._required ">
Confirmation Required
</p>
</div>
</div>

</form>
</div>

关于javascript - Angular 控制表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26990734/

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