I'm trying to implement a solution which would allow to display a list of violations for the field which mouse is over in a form of a tooltip (if any). I'd like to use the data-tooltip-html-unsafe (the derivation of tooltip which displays html content correctly) for this. Of course I'd prefer to use a single directive like tooltip-validated which would apply all the necessary directives to such element (like data-tooltip-html-unsafe) along with any logic needed (such as translations and so on). I managed to achieve my goals with the following code but there's a bug which is extremely difficult to track.
Here's the directive:
'use strict';
angular.module('example.common.directives')
.directive('tooltipValidated', ['$translate', '$timeout', '$compile', function ($translate, $timeout, $compile) {
function parseMessage(prefix, errors) {
// skipped some logic here
return 'parsed message';
}
return {
restrict: 'A',
require: 'ngModel',
replace: true,
link: function($scope, $element, $attributes, $ctrl) {
$attributes.$set('data-tooltip-html-unsafe', "{{errorMessage}}");
$attributes.$set('tooltip-trigger', "{{{true: 'mouseenter', false: 'never'}[memberForm.secondaryContact.$invalid]}}");
$scope.$watch(function() {
return $ctrl.$valid;
}, function(newValue) {
if(newValue) {
} else if($ctrl.$dirty) {
var errorMap = $ctrl.$error;
var prefix = $attributes.errorPrefix;
var message = parseMessage(prefix, errorMap);
$timeout(function() {
$scope.errorMessage = message;
});
}
});
$timeout(function() {
$element.removeAttr("tooltip-validated");
$compile($element)($scope); // this is what seems to cause the bug
});
}
}
}]);
And here's how am I using it:
<input type="email"
name="secondaryContact"
ng-model="member.secondaryContact"
ng-disabled="!editable"
class="g-input-text g-float-left"
ng-class="inputClass"
required
tooltip-validated
error-prefix="MEMBER_FORM.SECONDARY_CONTACT"
maxlength="30"/>
The problem is when the validation state changes (in either direction that is from invalid to valid and valid to invalid) the input gets cleared. This does not happen if
$compile($element)($scope);
is removed but then the tooltip doesn't get rendered. Why this line is causing such issue and how to come around this? Am I doing something wrong?
My solution is based on this and this
Thanks!