{"id":194,"date":"2016-05-08T06:03:49","date_gmt":"2016-05-08T06:03:49","guid":{"rendered":"http:\/\/muthu.co\/?p=194"},"modified":"2021-01-02T14:06:02","modified_gmt":"2021-01-02T14:06:02","slug":"contenteditable-div-tag-directive","status":"publish","type":"post","link":"http:\/\/write.muthu.co\/contenteditable-div-tag-directive\/","title":{"rendered":"contenteditable DIV tag directive"},"content":{"rendered":"

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.<\/p>\n

myApp.directive(\"contenteditable\", function() {\r\n  return {\r\n    restrict: \"A\",\r\n    require: \"ngModel\",\r\n    link: function(scope, element, attrs, ngModel) {\r\n\r\n      function read() {\r\n        ngModel.$setViewValue(element.html());\r\n      }\r\n\r\n      ngModel.$render = function() {\r\n        element.html(ngModel.$viewValue || \"\");\r\n      };\r\n\r\n      element.bind(\"blur keyup change\", function() {\r\n        scope.$apply(read);\r\n      });\r\n    }\r\n  };\r\n});<\/pre>\n

To turn your\u00a0div into an editor all you \u00a0need is to add contenteditable attribute to your div.<\/p>\n

<div contenteditable><\/div><\/pre>\n

See the editor live: Angular Directive for making simple WYSWYG Editor<\/a> by Muthukrishnan (@Muthukrishnan<\/a>) on CodePen<\/a>.<\/p>\n