如何在Angular js中使用ng-bind-html实现对contenteditable元素的双向绑定?

use*_*788 5 html javascript binding two-way angularjs

我刚刚开始讨论Angularjs,并在文档中看到了下面的内容,我如何调整它以使用ng-bind-html作为与ng-model相反的方法.我假设同时使用ng-bind-html和ng-model会发生冲突?

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);
        }
      }
    };
  });
Run Code Online (Sandbox Code Playgroud)

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

我目前正在使用如下的ng-bind-html指令(虽然不是双向绑定但效果很好):

<div ng-bind-html="person.nameHtml" contenteditable="true"></div>
Run Code Online (Sandbox Code Playgroud)

小智 2

根据问题的评论,答案是您可以使用该ngModel指令:

<div ng-bind-html="person.nameHtml"
     contenteditable="true"
     ng-model="person.nameHtml">
</div>
Run Code Online (Sandbox Code Playgroud)

  • 请注意,当 div 内容任何子元素(例如 &lt;b&gt; 标签为 ex )时,新字符将插入左侧而不是右侧 (2认同)