【问题标题】:AngularJS $compile and external directive ui-codemirrorAngularJS $compile 和外部指令 ui-codemirror
【发布时间】:2016-01-26 03:05:41
【问题描述】:

我正在尝试使用外部模块angular-ui-codemirror,使用嵌套指令ui-codemirror 在代码格式块中显示封闭AngularJS 指令的$element.html()

如果你想知道我为什么需要这样做,请查看here

我可以从示例中轻松了解如何使用静态文本来实现这一点。我可以通过封闭指令的innerHTML 好吧。它只是不会在之后编译成 ui-codemirror 指令。

我知道,here,可能需要使用$compile 服务来执行此操作,但我无法使该示例适应这种情况。

这里是一些示例 AngularJS 代码:

angular.module('articles', ['ui.codemirror']).directive('jsCode', function($compile) {
  return {
    restrict: 'E',
    link: function($scope, $element) {    
      $scope.codeText = $element.html();
      var template = '<div ' +
          'ui-codemirror="{ ' +
            'lineNumbers: true, ' +
            'theme:\'twilight\', ' +
            'readOnly: \'nocursor\', ' +
            'lineWrapping: true, ' +
            'mode: \'xml\'}" ' +
          'ng-bind="codeText"></div>';
      var linkFn = $compile(template);
      var content = linkFn($scope);
      $element.replaceWith(content)
    }
  };
});

和html:

<js-code>
&lt;html style=&quot;color: green&quot;&gt;
&lt;!-- this is a comment --&gt;
&lt;head&gt;
&lt;title&gt;HTML Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
The indentation tries to be &lt;em&gt;somewhat &amp;quot;do what
I mean&amp;quot;&lt;/em&gt;... but might not match your style.
&lt;/body&gt;
&lt;/html&gt;
</js-code>

我创建了this Plunker 来说明我的困境。第一个块未格式化。第二个块(静态)被格式化。

【问题讨论】:

  • 您是否需要/想要使用codeText 变量绑定html?换句话说,该变量的内容会在元素之外发生变化吗?如果不是,您可以在构建模板字符串时使用$element.html() - 但我认为codemirror lib中的某些内容依赖于已经在dom中的元素,因此即使在您单击其中之后它也不能完全正确地工作.看到这个plnkr.co/edit/2d3Y8Ic9XFbsloBgT7wv?p=preview

标签: angularjs angularjs-directive angularjs-compile ui-codemirror


【解决方案1】:

在 jsCode 指令中替换

'ng-bind="codeText"></div>';

通过

'ng-model="codeText"></div>';

并使用

$element.text()  

而不是

$element.html()

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 2021-08-19
    相关资源
    最近更新 更多