Skip to content

Instantly share code, notes, and snippets.

@virenratan
Created May 6, 2014 03:13
Show Gist options
  • Save virenratan/2a6869f3e48060e5cadc to your computer and use it in GitHub Desktop.
Save virenratan/2a6869f3e48060e5cadc to your computer and use it in GitHub Desktop.
Contenteditable element which respects maxlength attribute
app.directive('contenteditable', ['$timeout', function($timeout) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel',
scope: { model: '=ngModel' },
link: function(scope, element, attrs, ngModelCtrl) {
if( !ngModelCtrl ) return;
// model -> view
ngModelCtrl.$render = function() {
element.html(ngModelCtrl.$viewValue);
if (!ngModelCtrl.$viewValue) return;
angular.extend(scope, ngModelCtrl.$viewValue);
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
$timeout(read, 1);
// view -> model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if( attrs.stripBr && html === '<br>' ) {
html = '';
}
ngModelCtrl.$setViewValue(html);
}
// pushing model between two scopes on same element:
// http://stackoverflow.com/questions/15269737/why-is-ngmodel-setviewvalue-not-working-from/15272359#15272359
scope.$watch('model', function() {
scope.$eval(attrs.ngModel + ' = model');
});
// when the local model updates, perform parsing.
scope.$watch(attrs.ngModel, function( newValue ) {
if (typeof newValue === 'string') {
newValue = newValue.substring(0, attrs.maxlength);
}
$timeout(read, 1);
$timeout(function() {
scope.model = newValue;
ngModelCtrl.$modelValue = newValue;
}, 1);
});
/*
scope.$watch(function () {
return ngModelCtrl.$modelValue;
}, function(newValue) {
console.log(newValue);
});
ngModelCtrl.$formatters.push(function(value) {
console.log(value);
console.log(typeof value);
return (typeof value === 'string') ? value.substring(0, attrs.maxlength) : '';
});
element.bind('keydown', function() {
scope.$apply(function () {
console.log(ngModelCtrl.$viewValue);
//ngModelCtrl.$setViewValue(parseInt(ngModelCtrl.$viewValue, 10) + 1);
//ngModelCtrl.$render();
});
});
*/
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment