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

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

问题描述

我工作的一个项目,以渲染HTML采取特殊的XML作为输入。
我已经成功的基本情况。例如:

< myButton的名称=莱拉>< /为myButton>

被转换成

< D​​IV CLASS =BTN>与莱拉LT; / DIV>

使用指令就像

.directive('则myButton',函数(){
    返回{
        限制:'E',
        范围: {
            名称: '@'
        },
        templateUrl:'的UIComponents / uiButton.html
    }
})

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

< UI类型=back_buttonX =10.0Y =630.0/>

我想避免更改XML语法,但它可以在必要时进行。
所有的屏幕组件是在< UI>< / UI> 标记。在键入属性定义的组件。

你会如何写这样的标签指令?它似乎并不聪明,为创建一个巨大的指令< UI方式> 元素和内部具有的属性长的switch-case


解决方案

您可以创建一个基于转换的类型属性的元素,然后重新编译元素的UI指令 - 是这样的:

app.directive(UI,函数($编译){
  返回{
    限制:'E',
    编译:功能(tElement,tAttrs){
      如果(tAttrs.type){
        tElement.attr(tAttrs.type,'');
        tElement.removeAttr(类型);
        返回功能(范围,EL){
          $编译(EL)(范围);
        }
      }    }
  }
});
app.directive('后退按钮',函数(){
  返回{
    更换:真实,
    模板:'<按钮NG点击=btnClick()>将后退按钮模板< /按钮>'
  }
});

编辑:在我原来的例子中,我做编译模板元素的错误 - 如果是在ngRepeat正在使用的指令,这是不行的。解决方法是简单,编译链接元素来代替。我已经更新了code和例子。

查看这个plnkr例子

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>

is converted to

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

using a directive like

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

The real XML input I'll receive is:

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

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.

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.

解决方案

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>'
  }
});

Edit: 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.

Check out this plnkr example.

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

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