Is it possible to use ng-model with contenteditable?

Asked

Viewed 255 times

4

I need to use a divwith the attribute contenteditable and the result of that precise value put in a ng-model.

I did so, but it seems not to be working as expected:

<div contenteditable ng-model="observacao"></div>

How to make it work?

  • 2

    Already answered this a while ago here is the link I hope to have helped hug! https://stackoverflow.com/questions/28583651/contenteditable-with-ng-model-doesnt-work

2 answers

4


The tag contenteditable will not work directly with the ng-model of Angularjs because the rendering way updates the element in the document at each change.

You must involve him with a Directive customized for this:

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>Troque me!</div>
  <span ng-show="myForm.myWidget.$error.required">Obrigatorio!</span>
 <hr>
 <textarea ng-model="userContent"></textarea>
</form>

source

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.