我有页面设置,我想动态创建指令并将它们添加到页面。我已经完成了这项工作,但是在我添加的指令中没有正确编译,因为没有进行插值并且构造函数中的依赖性没有被加载。
以下是我正在使用的代码。
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.dashboardPartDataService的依赖关系返回undefined
答案 0 :(得分:0)
我遇到的问题是在调用构造函数之前调用了dashboardPartId的属性设置器,这导致who组件错误输出,因为this.dataService未定义。一旦我重构了set的加载并检查了dataService并将相同的调用添加到构造函数中,一切正常。