Building Advanced Directives
Most of the time AngularJS takes care of interpolating strings into expressions,
that is, when using {{}} brackets in templates. But in this directive we need to
programmatically interpolate a string. This is done with the $interpolate service.
Using the $interpolate service
The getLabelContent simply copies across the HTML content from the label
in the directive to the label in the template, where it will be compiled along with
the template:
function getLabelContent(element) {
var label = element.find('label');
return label[0] && label.html();
}
But for validation messages, we are going to use ng-repeat to display strings
only for validations that are currently failing. So we will need to store the
validation messages on the template's scope, as $validationMessages. These
validation messages may contain interpolated strings so we will interpolate them
during compilation:
function getValidationMessageMap(element) {
var messageFns = {};
var validators = element.find('validator');
angular.forEach(validators, function(validator) {
validator = angular.element(validator);
messageFns[validator.attr('key')] =
$interpolate(validator.text());
});
return messageFns;
}
For each of the
interpolation function from the text of the element and add that function into a map
based on the value of the validator element's key attribute. This map will be added
to the template's scope as $validationMessages.
The $interpolate service is used throughout AngularJS to evaluate strings that
contain {{}} curly braces. If we pass such a string to the service, it returns an
interpolation function that takes a scope and returns the interpolated string:
var getFullName = $interpolate('{{first}}{{last}}');
var scope = { first:'Pete',last:'Bacon Darwin' };
var fullName = getFullName(scope);