Mastering Web Application

(Rick Simeone) #1

Building Your Own Directives


$scope.$digest();
testInput.$setViewValue('[email protected]');
expect(Users.query).not.toHaveBeenCalled();
testInput.$setViewValue('[email protected]');
expect(Users.query).toHaveBeenCalled();

querySpy.reset();
testInput.$setViewValue('[email protected]');
expect(Users.query).not.toHaveBeenCalled();
$scope.model.testValue = '[email protected]';
$scope.$digest();
testInput.$setViewValue('[email protected]');
expect(Users.query).toHaveBeenCalled();
});

We set the model and then check that User.query() is called only if the input value
is set to an e-mail that does not match the original model value. We use Users.
query.reset() when we want to check that the spy has not been called since the
last time we checked.


Implementing the asynchronous validation directive


The implementation of this directive is similar in structure to the previous validation
directive. We require the ngModel controller and add to the $parsers and
$formatters in the linking function:


myModule.directive('uniqueEmail', ["Users", function (Users) {
return {
require:'ngModel',
link:function (scope, element, attrs, ngModelCtrl) {
var original;
ngModelCtrl.$formatters.unshift(function(modelValue) {
original = modelValue;
return modelValue;
});

ngModelCtrl.$parsers.push(function (viewValue) {
if (viewValue && viewValue !== original ) {
Users.query({email:viewValue}, function (users) {
if (users.length === 0) {
ngModelCtrl.$setValidity('uniqueEmail', true);
} else {
Free download pdf