in Angularjs, Javascript

contenteditable DIV tag directive

Are you looking for a super simple WYSWYG editor and you don’t want to include any heavy library into your application. Then why not make your own using just a div. Take a look at the below directive.

myApp.directive("contenteditable", function() {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attrs, ngModel) {

      function read() {
        ngModel.$setViewValue(element.html());
      }

      ngModel.$render = function() {
        element.html(ngModel.$viewValue || "");
      };

      element.bind("blur keyup change", function() {
        scope.$apply(read);
      });
    }
  };
});

To turn your div into an editor all you  need is to add contenteditable attribute to your div.

<div contenteditable></div>

See the editor live: Angular Directive for making simple WYSWYG Editor by Muthukrishnan (@Muthukrishnan) on CodePen.

Write a Comment

Comment