Mastering Web Application

(Rick Simeone) #1

Building Advanced Directives


Setting up the field template


In the field directive's link function, we call loadTemplate with the value of the
template attribute on the directive's element (or 'input.html' if none is specified).


loadTemplate(template).then(function(templateElement) {

All the work of the directive happens once the promise is resolved.


var childScope = scope.$new();
childScope.$validationMessages = angular.copy(validationMsgs);
childScope.$fieldId = attrs.ngModel.replace('.', '_').toLowerCase()
+ '_' + childScope.$id;
childScope.$fieldLabel = labelContent;

childScope.$watch('$field.$dirty && $field.$error',
function(errorList) {
childScope.$fieldErrors = [];
angular.forEach(errorList, function(invalid, key) {
if ( invalid ) {
childScope.$fieldErrors.push(key);
}
});
}, true);

First we create a new child scope and attach useful properties, such as
$validationMessages, $fieldId, $fieldLabel, and $fieldErrors:


var inputElement = findInputElement(templateElement);
angular.forEach(attrs.$attr, function (original, normalized) {
var value = element.attr(original);
inputElement.attr(original, value);
});
inputElement.attr('name', childScope.$fieldId);
inputElement.attr('id', childScope.$fieldId);

We copy over all the attributes from the field directive's element to the template's
input element and add on computed values for the name and id attributes:


var labelElement = templateElement.find('label');
labelElement.attr('for', childScope.$fieldId);
labelElement.html(labelContent);
Free download pdf