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

标签 javascript html angularjs binding two-way

我刚刚开始了解 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);
        }
      }
    };
  });

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

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

<div ng-bind-html="person.nameHtml" contenteditable="true"></div>

最佳答案

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

<div ng-bind-html="person.nameHtml"
     contenteditable="true"
     ng-model="person.nameHtml">
</div>

关于javascript - 如何在 Angular js 中使用 ng-bind-html 实现对 contenteditable 元素的双向绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23445516/

相关文章:

javascript - javascript中的形状类?

javascript - 使用 jQuery 填充子属性

javascript - 使用 Controller js 代码中的分层 json 对象应用 Angular Filter

php - 运行 ionic 应用程序时出现无法加载资源:net::ERR_CONNECTION_REFUSED

javascript - 将数据发布到服务器 Angular $http post

javascript - Ext Js 添加事件到 html 元素

html - 如何为我的报纸网站自动生成 "related articles"?

javascript - 沿相反方向旋转两个图像

html - mozilla 中的滚动条

angularjs - 如何确保服务中的 $http.get 在指令用数据初始化之前完成?