首页 > 解决方案 > 从 AngularJS 中的 pre-tag 获取更新的内容

问题描述

我有一个绑定到 FileReader-Result 的预标签来解析文本。该标签是可编辑的,我想在单击按钮后获取更新的内容。不幸的是,我总是得到原始文本内容。

HTML

<pre contenteditable="true" id="rangy" class="document-content textareac"
     ng-bind="vm.document.content" ng-hide="document.mode=='edit'"
     contenteditable>
</pre>  

JS

var txt = vm.document.content;

我试图通过查询选择来获取它,但它不起作用。它给了我一个 HTML 对象。

t = angular.element(document.querySelector('#rangy'));
alert(t);
// alert(JSON.stringify(t);

标签: angularjs

解决方案


AngularJS 文档有一个为元素contenteditable启用指令的指令示例。ng-model

app.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

 <div contenteditable
      name="myWidget" ng-model="userContent"
      strip-br="true"
      required>Change me!</div>

有关详细信息,请参阅


推荐阅读