2016-11-22 45 views
0

ディレクティブを動的に作成してページに追加するページ設定があります。私はこの作業を手に入れましたが、ディレクティブでは補間が発生せず、コンストラクタの依存関係がロードされていないため、正しく追加されません。ディレクティブの角度の動的作成

ここに私が使用しているコードがあります。

page.html

<dashboard-dynamic-component ng-repeat="item in vm.parts" dashboard-part="item.part.implementationComponent" dashboard-part-id="item.id"</dashboard-dynamic-component> 

dashboardDynamicComponent

function dynamicComponent($compile: ng.ICompileService, $timeout: ng.ITimeoutService) { 

    return { 
     restrict: 'E', 
     replace: true, 
     templateUrl: 'app/main/dashboard/dynamicComponent.html', 
     scope: { 
      dashboardPart: '=', 
      dashboardPartId: '=' 
     }, 
     link: (scope, element) => { 
      var newElement = $compile(`<${scope.dashboardPart} dashboard-part-id="${scope.dashboardPartId}" />`)(scope); 
      element.append(newElement); 
      $timeout(() => {}); 
     } 
    } 

} 
dynamicComponent.$inject = ['$compile', '$timeout']; 

angular.module('Cranalytics') 
    .directive('dashboardDynamicComponent', dynamicComponent); 

これは、しかし、私はそれを期待してコンポーネントを作成するには、次の部分で、私は問題を見たです。

titleComponent.html - だから私は、私はを取得していますので、私はただ一つの小さな部分が欠けていると思う動的

<h3 class="title">****{{vm.title}}****</h3> 

titleComponent.ts

export class TitleComponent implements ng.IDirective { 

    restrict = 'E'; 
    replace = true; 
    templateUrl = 'app/main/dashboard/titleComponent/titleComponent.html'; 
    scope = { 
     dashboardPartId: '=' 
    }; 
    controller = TitleController; 
    controllerAs = 'vm'; 
    bindToController = true; 

    static create(): ng.IDirectiveFactory { 
     const directive =() => new TitleComponent(); 
     return directive; 
    } 
    static instance(): ng.IDirective { return new TitleComponent(); } 
} 

export class TitleController { 

    _dashboardPartId: number; 
    get dashboardPartId(): number { 
     return this._dashboardPartId; 
    } 
    set dashboardPartId(value: number) { 
     this._dashboardPartId = value; 
     if (!value) return; 

     this.dataService.loadById(value) 
      .then((result: Models.Dashboard.dashboardPart) => { 
       var options = JSON.parse(result.options); 
       this.title = options.Title; 
      }); 
    } 

    title: string; 

    static $inject = ['Cranalytics.Dashboard.dashboardPartDataService']; 
    constructor(private dataService: Dashboard.dashboardPartDataService) {} 
} 

angular.module('Cranalytics') 
    .directive('dashboardTitleComponent', TitleComponent.create()); 

上に作成されているものです{{vm.title}}がページに表示されますが、補間は表示されません。また、上記のコードのコンストラクタでは、Cranalytics.Dashboard.dashboardPartDataS erviceが未定義に戻ります

答えて

0

この問題は、コンストラクタが呼び出される前にdashboardPartIdのプロパティ設定ツールが呼び出されていて、this.dataServiceが定義されていないためにwhoコンポーネントがエラーになるという問題でした。一度私はセットの読み込みをリファクタリングし、dataServiceをチェックして、同じコールをコンストラクタに追加してすべてを動かしました。

関連する問題