15

I'm trying to store the value of a contenteditable to my JS code. But I can't find out why ng-model doesn't work in this case.

<div ng-app="Demo" ng-controller="main">
    <input ng-model="inputValue"></input>
    <div>{{inputValue}}</div> // Works fine with an input
    <hr/>
    <div contenteditable="true" ng-model="contentValue"></div>
    <div>{{contentValue}}</div> // Doesn't work with a contenteditable
</div>

Is there a workaround to do that ?

See : JSFiddle

Note: I'm creating a Text editor, so the user should see the result, while I'm storing the HTML behind it. (ie. user see: "This is an example !", while I store: This is an <b>example</b> !)

3 Answers 3

33

contenteditable tag will not work directly with angular's ng-model because the way contenteditable rerender the dom element on every change.

You have to wrap it with a custom directive for that:

JS:

angular.module('customControl', ['ngSanitize']).
directive('contenteditable', ['$sce', function($sce) {
  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($sce.getTrustedHtml(ngModel.$viewValue || ''));
      };

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

      // Write data to the 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 = '';
        }
        ngModel.$setViewValue(html);
      }
    }
  };
}]);

HTML

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

Source it from the original docs

5
  • I already saw this code in the doc, but didn't understand its use correctly, your few lines made me understand. =)
    – Elfayer
    Commented Feb 18, 2015 at 13:28
  • 7
    It doesn't render ng-model value. Let's say instead of static text "Change me!" I have a variable it shows variable as is.
    – Dmitry
    Commented Jul 27, 2015 at 20:36
  • 3
    @Ben Diamant: As soon as start editing the contenteditable div, on every keystroke my cursor goes to the start of the div. Have to click at the desired location to edit again. Commented Aug 18, 2015 at 11:31
  • this answers code is similar as that of angular docs example Commented Mar 31, 2017 at 20:46
  • using AngularJS v1.6.7 and ngSanitizeis throwing an $injector:modulerr Module Error
    – shadownrun
    Commented Jan 28, 2018 at 23:38
8

Just move the read function call into $render

angular.module('customControl', ['ngSanitize']).
directive('contenteditable', ['$sce', function($sce) {
  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($sce.getTrustedHtml(ngModel.$viewValue || ''));
        read(); // initialize
      };

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

      // Write data to the 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 = '';
        }
        ngModel.$setViewValue(html);
      }
    }
  };
}]);
3
  • Why is this wrong in the original AngularJS example?
    – fishbone
    Commented Apr 10, 2017 at 7:43
  • It works because you have to set the viewValue after rendering or the view won't reflect changes to the model, and moving the read function call into $render achieves just that
    – goonerify
    Commented Apr 10, 2017 at 13:35
  • I just wonder why they didn't do it this way in their example, because this makes much more sense
    – fishbone
    Commented Apr 10, 2017 at 16:33
0

Neither of the other answers worked for me. I needed the model's initial value to be rendered when the control was initialized. Instead of calling read(), I used this code inside the link function:

ngModel.$modelValue = scope.$eval(attrs.ngModel);
ngModel.$setViewValue(ngModel.$modelValue);
ngModel.$render()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.