简体   繁体   English

在自定义Angular指令中,将innerHTML作为属性传递给另一个指令

[英]In a custom Angular directive, pass the innerHTML as an attribute to another directive

I am trying to take the innerHTML of an Angular directive, and pass that as an attribute of another directive. 我正在尝试采用Angular指令的innerHTML,并将其作为另一个指令的属性传递。 So, let's say that I have: 因此,假设我有:

<js-code>This is some text</js-code>

my jsCode directive looks like this: 我的jsCode指令如下所示:

prettifyModule.directive('jsCode', function() {
  return {
    restrict: 'E',
    compile: function($element, $scope) {
      $scope.codeText = $element.html();
      $element.replaceWith("<code-mirror model='codeText'></code-mirror>");
    }
  };
});

The goal being to pass a variable containing the string, "This is some text" as the model attribute of the code-mirror directive. 目标是传递包含字符串“ This is some text”的变量作为code-mirror指令的model属性。 For the most part, this seems to work. 在大多数情况下,这似乎可行。 I can see in the elements that a directive appears that looks like: 我可以在元素中看到伪指令看起来像:

<code-mirror model='codeText'></code-mirror>

However, the controller for the code-mirror directive does not, at that point, initialize. 但是,此时代码镜像指令的控制器未初始化。

If anyone could point out what I am doing wrong, or if there is a better way to do this entirely, it would be appreciated. 如果有人指出我做错了什么,或者有更好的方法可以完全做到这一点,将不胜感激。

My limitations are: 我的限制是:

  • I cannot alter the code-mirror directive. 我无法更改code-mirror指令。
  • I cannot statically manipulate the text that is being sent to the jsCode directive. 我无法静态地处理发送到jsCode指令的文本。

I have changed the directive code to 我已将指令代码更改为

myApp.directive('myDirective', function($compile) {
return {
restrict: 'E',
link: function($scope, $element){
        $scope.codeText = $element.html();
      var template = "<second-directive model='codeText'></second-directive>";
      var linkFn = $compile(template);
      var content = linkFn($scope);
      $element.replaceWith(content);
},
controller: function($scope) {
  $scope.test = "Text from controller";
}
};
});

Here is the updated fiddle http://jsfiddle.net/xw7ms0xd/2 This is the first time, I used $compile service. 这是更新的小提琴http://jsfiddle.net/xw7ms0xd/2这是我第一次使用$ compile服务。 Got the reference from here http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx 从这里获得参考http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM