I am trying to create directive which can be used to compare two fields in multiple projects.
MarkUp :
<div class="form-group">
<input ng-model="user.password" type="password" name="password" />
</div>
<div class="form-group">
<input ng-model="user.confpassword" ng-compare="password" name="confpassword" type="password" />
<p ng-show="registrationform.password.$error.ngcompare" class="help-block">Password's don't match</p>
Directive :
"use strict";
angular.module('app.directive.ngCompare', []).directive('ngCompare', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ngModelController)
{
ngModelController.$parsers.unshift(function (viewvalue) {
console.log(scope); // doesnot contain password field object
console.log(viewvalue); // gives me value of confpassword field
console.log(scope[attrs.ngCompare]); // undefined
});
}
}});
I have not completed writing my directive but , during development when i console scope i dont get value of first password but i get value of confpassword.i am including this direcitive in my main app as 'app.directive.ngCompare'.Is it because of that i dont get value of password.
I am using angular version 1.3.9. I know there are many similar directives out there but i need to figure out step by step how they run so started creating from scratch.Is there any other way to get value of password using angularjs techiques rather than jquery methods.
The problem with the answers given so far is that they all create an isolate scope. This means you couldn't use additional directives on the same input or on another directive.
That can be fixed by modifying the above as follows:
.directive("compareTo", function() {
return {
require: "ngModel",
link: function(scope, element, attrs, ctrl) {
ctrl.$validators.compareTo = function(val) {
return val == scope.$eval(attrs.compareTo);
};
scope.$watch(attrs.compareTo, function() {
ctrl.$validate();
});
}
};
});