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

时间:2016-07-03 20:23:14

标签: 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!
      }
   }
}

那么我还能做些什么才能访问该属性?

1 个答案:

答案 0 :(得分:6)

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

这是AngularJS中使用Javascript的示例,其中模板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';
  }
});

模板摘录:

<my-component use-template="hui.html"></my-component>
<my-component use-template="bu.html"></my-component>
<p></p>
<my-component></my-component>

工作示例: template injection in an angular 1.5 component