在 Angular 指令中获取原始嵌入内容 [英] Get original transcluded content in Angular directive

查看:44
本文介绍了在 Angular 指令中获取原始嵌入内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以以编程方式获取 Angular.js 指令中的原始嵌入内容?

我正在尝试创建一个 editable 指令,该指令可以添加到任何 div,允许用户使用自定义角度指令编辑 HTML 内容.(设计目标是避免需要在应用程序中添加无限配置 GUI 功能,因为高级用户只需编辑 HTML...),例如:

 

<h1>Lorem Ipsem</h1><p>Lorem ipsum dolor sat amet, consectetur adipisicing 精英...</p><clock>自定义指令</clock>

以这个Plunker为例(http://plnkr.co/edit/nIrr9Lu0PZN2PdnhQOC6?p=预览):

  • 点击灰色实心条上的编辑图标打开编辑器
  • 输入任何带有标签的格式良好的 HTML:(例如

    一个标题

    一些内容

    )
  • 点击应用"

到目前为止我喜欢这个:

  • 它可以添加到任何div
  • 它可以包含嵌套的自定义指令,通过使用 $compile
  • 它包括嵌入的内容

我还想不通:

  • 如何获取原始嵌入内容来初始化textarea

在编译函数中,$transclude 似乎包含了 mydirective 的模板,而在控制器函数中,$transclude 包含了 post- 在更改内容、呈现指令等之后编译的内容

解决方案

可以使用transclude函数:

.directive('editable', function() {返回 {转置:真实,链接:函数(范围,元素,属性,ctrl,transclude){transclude(范围,功能(克隆){//克隆是你的转译内容});}};});

Is it possible to programmatically get the original transcluded content within an Angular.js directive?

I'm trying to create an an editable directive which can be added to any div, allowing the user to edit the HTML content with custom angular directives. (The design goal is to avoid the need to add infinite configuration GUI features in the app, as power users can just edit the HTML...), e.g.:

 <div editable>
      <h1>Lorem Ipsem</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <clock>A custom directive</clock>
 </div>

See this Plunker as an example (http://plnkr.co/edit/nIrr9Lu0PZN2PdnhQOC6?p=preview):

  • Click the edit icon on the solid grey bar to open the editor
  • Enter in any well formed HTML with tags: (e.g. <h1>A title</h1><p>some content</p><clock></clock>)
  • Click "Apply"

What I like about this so far:

  • It can be added to any div
  • It can include nested custom directives, by using $compile
  • It includes the transcluded content

What I can't figure out yet:

  • How to get the raw transcluded content to initialize the textarea

Within the compile function, $transclude seems to contain the template for mydirective, and with the controller function, $transclude contains the post-compiled content after things have been changed, directives rendered, etc.

解决方案

You can use transclude function:

.directive('editable', function() {
    return {
       transclude: true,
       link: function(scope, element, attrs, ctrl, transclude) {
           transclude(scope, function(clone) {
               // clone is your transluded content
           });
       }
    };
});

这篇关于在 Angular 指令中获取原始嵌入内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆