Ok, so I have an input field that i would like to enhance with 2 custom directives:
<input type="text" number-format validation-message="Only numeric values are valid!" class="form-control" id="num1" ng-model="num1" />
The first directive validates any input on the moment of entering text -> in this case I check for numbers with a regex: (this is actually working fine)
.directive('numberFormat', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var invalidNumber = /^[0-9]+$/.test(viewValue);
if (invalidNumber || viewValue === ''){
ctrl.$setValidity('numberFormat', true);
} else {
ctrl.$setValidity('numberFormat', false);
}
});
}
};})
And then, I tought it might be useful to have a tooltip displayed saying that only numbers are valid for this input field. And i would like to show it in the moment of the validation failing. The 2nd directive that I have so far looks like this:
.directive('validationMessage', function () {
return{
restrict: 'A',
template: '<input tooltip tooltip-placement="bottom" >',
replace: true,
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
var valid = ctrl.$valid;
if (valid) {
attrs.$set('tooltip', "");
} else {
attrs.$set('tooltip', attrs.validationMessage);
scope.tt_isOpen = true; // doesn't work!?
}
return viewValue;
});
}
};})
Well, basically it does work in the way, that the tooltip and tooltip-placement attributes are updated to the input element. But for some reason the tooltip is not shown immediately when the validity has failed (and the tooltip attribute with its text is set). The user needs to hover out and back in the input element by the mouse to see the tooltip.
I've created a plunker for a better visualisation of this behaviour: http://plnkr.co/edit/3QOiOom6VQm3cXAstB3j?p=info
I tried 'scope.tt_isOpen' but it does not seem to have any effect. What exactly am i missing to show the tooltip?
Many thanks for every tip.