Skip to content

Instantly share code, notes, and snippets.

@arodbits
Created October 17, 2014 19:41
Show Gist options
  • Save arodbits/3fd72b3c02caf6bd37cd to your computer and use it in GitHub Desktop.
Save arodbits/3fd72b3c02caf6bd37cd to your computer and use it in GitHub Desktop.
A Pen by Anthony.
<!-- Login form -->
<div ng-app="myLoginApp">
<h1>REGISTER</h1>
<p>Input your credentials here</p>
<form name="registerForm">
<div>
<input ng-model="username" type="text" placeholder="Username"/>
</div>
<div>
<input ng-model="password" type="password" placeholder="Password"/>
</div>
<div>
<input name="confirmPassword" ng-model="confirmPassword" type="password" match="password" placeholder="Confirm Password"/>
</div>
<div ng-show="registerForm.confirmPassword.$error.match">The passwords don't match!</div>
<div>
<button type="submit" ng-submit="doLogin()">Log in</button>
</div>
</form>
</div>
/*Author: Anthony Rodriguez
Match directive.
2014
MTI LICENCE
*/
//Creating myLoginApp module
var app = angular.module('myLoginApp', []);
// Match directive
/*
Match directive will be using the $watch function to listen to any model mutation (changes to the model), comparing the values in password and confirmPassword, if the values matches, then the watchExpression will return true, passing the result to the listen function.
In our example, match will be an attribute contained in the confirmPassword element. The value passed to match references to the model "password" deffined before.
*/
app.directive('match', function(){
return {
require : 'ngModel',
restrict : 'A',
scope : {
match : "="
},
link : function(scope, element, attr, ctrl){
var watchFunction = function(){
var blank = angular.isUndefined(scope.match) && angular.isUndefined(ctrl.$modelValue);
//-Defining the validity--
// True when the form is initially blank.
// True when the values are equal
// Treu when the value of the models are different and the value of confirmPassword == ""
return (blank) || ctrl.$modelValue == scope.match || ctrl.$modelValue != scope.match && (ctrl.$modelValue=="");
};
var listener = function(itMatch){
ctrl.$setValidity('match', itMatch);
};
scope.$watch(watchFunction, listener);
}
};
});

Watch

This time we'll be discussing the method $watch in Angularjs. Let's make our form to inform the user if the password and confirm password match. To achieve it will be creating a new directive and will explain all the elements involved. Have fun!

A Pen by Anthony on CodePen.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment