具有特定类型的通用指令(UI 组件继承) [英] A general directive with a specific type (UI components inheritance)

查看:31
本文介绍了具有特定类型的通用指令(UI 组件继承)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,以使用特殊的 XML 作为输入来呈现 HTML.我已经在基本案例中取得了成功.例如:

I'm working on a project to render HTML taking a special XML as input. I succeed already with the basic case. For example:

<mybutton name="layla"></mybutton>

转换为

<div class="btn">Layla</div>

使用类似的指令

.directive('mybutton', function() {
    return {
        restrict: 'E',
        scope: {
            name: '@'
        },
        templateUrl: 'uicomponents/uiButton.html'
    }
})

我将收到的真正 XML 输入是:

The real XML input I'll receive is:

<ui type="back_button" x="10.0" y="630.0"/>

我想避免更改 XML 语法,但可以在必要时完成.所有屏幕组件都在 标签中.type 属性定义了组件.

I'd like to avoid changing the XML syntax but it can be done if necessary. all screen components are in <ui></ui> tags. The type attribute defines the component.

您将如何为此类标签编写指令?为 <ui> 元素创建一个巨大的指令并在内部为属性设置一个长的 switch-case 似乎并不明智.

How would you write directives for this kind of tags? It doesn't seem smart to create one huge directive for <ui> elements and having a long switch-case inside for the attribute.

推荐答案

你可以创建一个 ui 指令,根据 type 属性转换元素,然后重新编译元素 - 像这样:

You could create a ui directive that transforms the element based on the type attribute and then recompiles the element - something like this:

app.directive('ui',function($compile){
  return {
    restrict:'E',
    compile:function(tElement,tAttrs){
      if(tAttrs.type){
        tElement.attr(tAttrs.type,'');
        tElement.removeAttr('type');
        return function(scope,el){
          $compile(el)(scope);
        }
      }

    }  
  }
});


app.directive('backButton',function(){
  return {
    replace:true,
    template:'<button ng-click="btnClick()">A back-button template</button>'
  }
});

在我的原始示例中,我犯了编译模板元素的错误 - 如果在 ngRepeat 中使用了该指令,则这将不起作用.修复很简单,而是编译链接元素.我已经更新了代码和示例.

In my original example I made the mistake of compiling the template element - this will not work if the directive is being used in a ngRepeat. The fix is simple, compile the link element instead. I've updated the code and the example.

查看这个plnkr示例.

这篇关于具有特定类型的通用指令(UI 组件继承)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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