So I have this form snippet:
<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>
And as you can see there is this registerForm.pwd
which is the form name plus the input name. Angular has added things like $error
and $dirty
to this variable.
Is there any way I can add my own to it? so like registerForm.pwd.$notEqual
via a directive?
Yes please see workink demo below.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.