Angular 1.5+组件 - 使用templateUrl函数内部的绑定

Cie*_*iel 4 angularjs typescript

我使用的是Angular 1.5+Typescript,准备我的代码是兼容Angular 2.我的情况是,我的许多组件需要使用应用程序范围的存储库位置来映射到其templateUrl属性的视图,但有时视图需要特定的本地实现.

因此,通常视图托管在快速服务的CDN上,它们在多个站点之间重复使用,这些站点都属于相同的通用代码库,api等.这样做是为了防止重复它们并集中管理什么.需要重复.

很少,我需要覆盖此行为并使用更具体,微调的视图.所以我的方法是binding在被调用的组件中添加一个viewLocation,意图像这样使用它;

<component-name></component-name>是默认值.在这种情况下,使用默认CDN路径. <component-name view-location="local"></component-name>是一种独特的情况.如果发生这种情况,templateUrl应该能够响应并切换到相对于特定应用程序而不是CDN的路径.

我认为这很简单,直到我意识到我无法访问实际构造函数或templateUrl函数中的绑定属性,如此处所示;

export class SidebarComponent extends Component {
   constructor() {
      super();
      this.bindings = { viewLocation: '=' };
      // other properties
      this.templateUrl = ($someService: IServiceInterface): string => {
         // help! I don't have access to the viewLocation property!
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

那么我有什么办法可以访问该属性吗?

sim*_*msi 7

这不是在TS中完成的,但是当您使用可注入模板时,AngularJS 1.5组件通常会为$ injector提供$ element和$ attrs.

这是使用Javascript的AngularJS中的示例,其中根据组件上设置的属性挑选模板URL:

angular.module('example', []);

angular.module('example').component('myComponent', {
  templateUrl: function($element, $attrs, $log) {

    $log.info('determining template to be used');

    if($attrs.useTemplate) {
      return $attrs.useTemplate;
    }

    return 'default.html';
  }
});
Run Code Online (Sandbox Code Playgroud)

模板片段:

<my-component use-template="hui.html"></my-component>
<my-component use-template="bu.html"></my-component>
<p></p>
<my-component></my-component>
Run Code Online (Sandbox Code Playgroud)

工作示例: 角度1.5组件中的模板注入

  • 在这种情况下它是.. :-)它由Angular提供作为"本地人"之一 - Angular为某些上下文提供的依赖关系,在这种情况下是模板注入 (2认同)