5

我刚刚开始掌握 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 指令,如下所示(虽然不是双向绑定,但效果很好):

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

1 回答 1

2

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

<div ng-bind-html="person.nameHtml"
     contenteditable="true"
     ng-model="person.nameHtml">
</div>
于 2014-07-31T03:14:30.160 回答