Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I achieve two way binding for a contenteditable element using ng-bind-html in Angular js?

I'm just getting to grips with Angularjs and have seen the below in the documentation, how can I adapt this to use ng-bind-html as oppose to ng-model. I assume using both ng-bind-html and ng-model together would conflict?

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.on('blur keyup change', function() {
          scope.$apply(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);
        }
      }
    };
  });

from https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

I am currently using the ng-bind-html directive as below (and works well although not two-way binding):

<div ng-bind-html="person.nameHtml" contenteditable="true"></div>
like image 663
user3197788 Avatar asked Nov 02 '22 00:11

user3197788


1 Answers

The answer, according to the comments on the question, is that you can use the ngModel directive:

<div ng-bind-html="person.nameHtml"
     contenteditable="true"
     ng-model="person.nameHtml">
</div>
like image 164
user9903 Avatar answered Nov 11 '22 04:11

user9903