Skip to content

Instantly share code, notes, and snippets.

@singhmohancs
Created January 27, 2017 09:32
Show Gist options
  • Save singhmohancs/ed77306b06a002f8f57ef1ffe7cfdf51 to your computer and use it in GitHub Desktop.
Save singhmohancs/ed77306b06a002f8f57ef1ffe7cfdf51 to your computer and use it in GitHub Desktop.
Toggle default value on focus and blur on text field
/**
* @ngdoc Directive
* @name defaultValue
* @restrict 'A'
* @element ANY
* @author Mohan Singh ( gmail::mslogicmaster@gmail.com, skype :: mohan.singh42 )
**/
(function () {
'use strict';
angular
.module('tallyfy')
.directive('defaultValue', ['_', function (_) { // '_' is a dependency for lodash
return {
restrict: 'A',
require: '^ngModel',
link: function (scope, element, attrs, modelCtrl) {
var currValue;
element.bind('focus', function (event) {
if (_.isEmpty(currValue)) {
currValue = modelCtrl.$modelValue;
}
if (currValue === modelCtrl.$modelValue) {
modelCtrl.$setViewValue('');
modelCtrl.$render();
}
});
element.bind('blur', function (event) {
if (_.isEmpty(modelCtrl.$modelValue)) {
modelCtrl.$setViewValue(currValue);
modelCtrl.$render();
}
});
scope.$on('$destroy', function () {
element.unbind('focus blur');
})
}
}
}]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment