When we need to provide some hint to the textbox, watermark text is an option. Watermark text provides some text as a hint to the user as to what they are going to enter. As soon as the text receives focus the watermark removes on its own and again reappears when it loses focus.
Let us see how to achieve this in angular Js. We need to create a custom directive which will be applied to the textbox which need to get watermark text.
Code:
- <!DOCTYPE html>
- <html>
- <head>
- <style type="text/css">
- .watermarkText
- {
- width: 145px;
- height: 24px;
- border: 1px solid #3366FF;
-
- }
- .watermark
- {
- font-weight: bold;
- }
- </style>
-
- <title>angularjs watermark for textbox</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"></script>
- <script>
- var app = angular.module('watermarkApp', []);
-
- app.controller('watermarkCtrl', function ($scope) {
- $scope.username = null;
- });
-
- app.directive('watermarkText', function ($timeout) {
- return {
- restrict: 'A',
- require: 'ngModel',
- link: function (scope, element, attr, ctrl) {
- $timeout(function () {
- var onFocus = function () {
- if (element.val() === attr.watermarkText) {
- element.val("");
- }
- element.removeClass('watermark');
- };
-
- var onBlur = function () {
-
- if (element.val() === "") {
- element.val(attr.watermarkText);
- element.addClass('watermark');
- }
- };
-
- if (attr.readonly !== true) {
- element.bind('focus', onFocus);
- element.bind('blur', onBlur);
- element.triggerHandler('blur');
- }
-
- scope.$watch(attr.ngModel, function (v) {
- onFocus();
- onBlur();
- });
-
- });
- }
- };
- });
-
- </script>
- </head>
- <body ng-app="watermarkApp" ng-controller="watermarkCtrl">
-
- <div style="height: 210px; width: 600px; border: 5px solid gray;">
- <h1>
- Water Mark Text in AngularJs</h1>
- <table>
- <tr>
- <td>
- User Name :
- <input type="text" ng-model="username" watermark-text="Enter your user Name....."
- class="watermarkText" />
- </td>
- </tr>
- <tr>
- <td>
- Password :
- <input type="text" ng-model="userpwd" watermark-text="Enter your password..." class="watermarkText" />
- </td>
- </tr>
- <tr>
- <td>
- <input type="submit" value="Save" />
- </td>
- </tr>
- </table>
- </div>
-
- </body>
- </html>
Hope you got the information on water mark text and how to achieve it in angular Js .Thank you for reading.