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');
}
//if the value changed programmatically, focus then blur to simulate the user entering the value so that the class is added or removed
scope.$watch(attr.ngModel, function (v) {
onFocus();
onBlur();
});
});
}
};
});
<!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="frmEmailCart">
Email : <input type="email" ng-model="useremail" email-watermark="Enter a Valid Email.." class="tb8"/>
</form>
</body>
</html>
/* Put your css in here */
.tb8 {
width: 245px; height:24px;
border: 1px solid #3366FF;
border-left: 1px solid #3366FF;
}