Hello everyone, I am going to share the code
sample for how to watermark for input text-box in Angularjs.
Here
we can achieve angular watermark
functionality using the creating custom directive which are give below.
Go to
live demo link http://embed.plnkr.co/cWynkpEgO08Oh2uUhVV0/preview
The HTML code is
<input type="email" ng-model="useremail" email-watermark="Enter a Valid
Email.."
/>
The AngularJs code is
var app =
angular.module('watermarkApp',
[]);
app.controller('watermarkCtrl', function ($scope) {
$scope.useremail = null;
});
app.directive('emailWatermark', function ($timeout) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element,
attr, ctrl) {
$timeout(function () {
var onFocus = function () {
if (element.val() ===
attr.emailWatermark) {
element.val("");
}
element.removeClass('watermark');
};
var onBlur = function () {
if (element.val() === "") {
element.val(attr.emailWatermark);
element.addClass('watermark');
}
};
if (attr.readonly !== true) {
element.bind('focus', onFocus);
element.bind('blur', onBlur);
element.triggerHandler('blur');
}
//Watching to the
value changed.
scope.$watch(attr.ngModel, function (v) {
onFocus();
onBlur();
});
});
}
};
});
The Live demo code(HTML + AngularJs)
as given below
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>angularjs watermark
for textbox</title>
<link rel="stylesheet" href="style.css" />
<script src="https://code.angularjs.org/1.4.3/angular.js"></script>
<script>
var app =
angular.module('watermarkApp',
[]);
app.controller('watermarkCtrl', function ($scope) {
$scope.useremail = null;
});
app.directive('emailWatermark', function ($timeout) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element,
attr, ctrl) {
$timeout(function () {
var onFocus = function () {
if (element.val() ===
attr.emailWatermark) {
element.val("");
}
element.removeClass('watermark');
};
var onBlur = function () {
if (element.val() === "") {
element.val(attr.emailWatermark);
element.addClass('watermark');
}
};
if (attr.readonly !== true) {
element.bind('focus', onFocus);
element.bind('blur', onBlur);
element.triggerHandler('blur');
}
//Watching to the
value changed.
scope.$watch(attr.ngModel, function (v) {
onFocus();
onBlur();
});
});
}
};
});
</script>
</head>
<body ng-app="watermarkApp" ng-controller="watermarkCtrl">
<h1>AngularJs watermark
for textbox</h1>
<form id="frmEmail">
Email : <input type="email" ng-model="useremail" email-watermark="Enter a Valid
Email.."
class="tb8" />
</form>
</body>
</html>
The output : go to link http://embed.plnkr.co/cWynkpEgO08Oh2uUhVV0/preview