In short, the aim is to streamline templating by avoiding manual addition of
for every individual ng-class={'has-error': 'formName.inputName.$invalid'}
form-group
The idea is to develop a directive that will automatically generate a string to append to a template element. This string will be an ng-class
attribute with an expression.
Initially, I believed that creating a simple directive during the compile phase to insert the ng-class attribute would suffice, but it appears insufficient.
Definition Object for Directive
{
restrict: 'C',
compile: function(tElement, tAttrs) {
var $elem = angular.element(tElement),
formName = $elem.parents('[ng-form]').length ? $elem.parents('[ng-form]').attr('ng-form') : $elem.parents('form').attr('name'),
controlName = $elem.find('.form-control').attr('name');
$elem.attr('ng-class', '{"has-error": ' + formName + '.' + controlName + '.$invalid}');
console.log('added ng-class attr', $elem.attr('ng-class'));
}
}
Check out the Plunk here
Take a look at the console output
The first
form-group
has the dynamic addition of itsng-class
attribute.
The associated expression is correct
However, the execution of theng-class
directive never occursThe second
form-group
manually adds itsng-class
attribute in the template and functions as expected.
--
What could be the missing piece here?