ngModel directive updation

by Arun P Johny

HTML

<form name="myForm" ng-app="customControl">
    <div ng-init="form.userContent"></div>
    <div contenteditable name="myWidget" ng-model="form.userContent" required>Change me!</div>
    <span ng-show="myForm.myWidget.$error.required">Required!</span>
    <hr />
    <textarea ng-model="form.userContent"></textarea>
</form>

CSS

[contenteditable] {
  border: 1px solid black;
  background-color: white;
  min-height: 20px;
}
 
.ng-invalid {
  border: 1px solid red;
}

JavaScript

angular.module('customControl', []).directive('contenteditable', function() {
	return {
		restrict : 'A', // only activate on element attribute
		require : '?ngModel', // get a hold of NgModelController
		link : function(scope, element, attrs, ngModel) {
			if (!ngModel)
				return; // do nothing if no ng-model

			// Specify how UI should be updated
			ngModel.$render = function() {
				element.html(ngModel.$viewValue || '');
			};

			// Listen for change events to enable binding
			element.bind('blur keyup change', function() {
						scope.$apply(read);
					});
			read(); // initialize

			// Write data to the model
			function read() {
				ngModel.$setViewValue(element.html());
			}
		}
	};
});