如何在模板中访问Angular 1.5的组件属性

How to access Angular 1.5 component property inside a template

本文关键字:组件 属性 Angular 访问      更新时间:2023-09-26

我正在尝试在Angular 1.5中实现一个简单的组件,我试图访问组件mycomponenheader '中的绑定(绑定)属性'compTitle'。

var mycomponentheader = {
    ....
    bindings: {
    'comptitle': '@mycomptitle'
    },
    ....
};

我在视图中的html标记中传递属性值[compTitle="encryptedTitle"]。

  <mycomponentheader mycomptitle="encryptedTitle">
    <div>    
      This is displayed for component content
    </div>
  </mycomponentheader>

当我尝试在指令中使用类似的机制时,它会起作用。相同的字符串是@ https://jsfiddle.net/visibleinvisibly/4n7vsas7/

我知道将模板属性定义为可以注入$element和$attrs的函数(template: function ($element, $attrs){}在Angular 1.5中),但我正在寻找其他方法。

Thanks in Advance

查看组件指南

您将看到,默认情况下,绑定绑定到controller,并且它们位于$ctrl下,而不是this下,因为使用了controllerAs

话虽如此,只需从$ctrl访问comptitle,如:$ctrl.comptitle

下面是工作演示。

注意:在组件的指南中,你会看到一个列表,列出组件和指令之间的主要区别。您将注意到,一些mycomponentheader属性是不需要的,因为它们不存在于组件中。这些属性包括:restrict(默认为E)和replace(不支持)。