AngularJS 1.6.x 使用 html 字符串和 ng-if="{{ }}" 动态加载组件

AngularJS 1.6.x Dynamically Load Components with html string and ng-if="{{ }}"

我在使用 Angular 1.6.x

通过 {{}} 动态加载组件时遇到问题

我可以使用编译动态加载组件,但我面临的问题是将 ng-if={{}} 添加到 html 字符串。

如果我走这条路,它将采用当时 vm.page 设置的值。即 1:

    for (var i = 0; i < vm.wizardPages.length; i++) {
     var newScope = $scope.$new(true, $scope);
     newScope = angular.merge(newScope, vm.wizardPages[i]);
     var html = '<' + vm.wizardPages[i].componentName + ' ng-if="' + 
     vm.page + ' === ' + (i + 1) + '"></' + vm.wizardPages[i].componentName 
     + '>';
     var element = $('page');
     element.append($compile(html)(newScope));
}

以上呈现:

<service-center-branch-selection ng-if="1 === 1" class="ng-scope ng-isolate-scope">
   ...
</service-center-branch-selection>

如何在字符串中使用 {{}} 调用编译,以便 vm.page 使用数据绑定并且可以在 vm.page 更改值时更改?:

// loop through the data and inject components
for (var i = 0; i < vm.wizardPages.length; i++) {
    var newScope = $scope.$new(true, $scope);
    newScope = angular.merge(newScope, vm.wizardPages[i]);
    var html = '<' + vm.wizardPages[i].componentName + ' ng-if="{{vm.page}} === ' + (i + 1) + '"></' + vm.wizardPages[i].componentName + '>';
    var element = $('page');
    element.append($compile(html)(newScope));
    console.log(newScope);
}

我希望以上内容适用于:

<service-center-branch-selection ng-if="vm.page === 1" class="ng-scope ng-isolate-scope">
   ...
</service-center-branch-selection>

改为"currentPage":

// loop through the data and inject components
for (var i = 0; i < vm.wizardPages.length; i++) {
    var newScope = $scope.$new(true, $scope);
    newScope = angular.merge(newScope, vm.wizardPages[i]);
    var html = '<' + vm.wizardPages[i].componentName + ' ng-if="currentPage === ' + (i + 1) + '"></' + vm.wizardPages[i].componentName + '>';
    var element = $('page');
    element.append($compile(html)(newScope));
    console.log(newScope);
}

添加 'currentPage' 绑定到组件以便可用于新范围:

app.component("wizard", { 
     template: require('./wizard.component.html'), 
     controllerAs: "vm", 
     controller: wizardController, 
     bindings: { 
          breadcrumbs: '<', 
          wizardPages: '<',
          currentPage: '<'
     } 
});

向标记添加变量输入

<wizard breadcrumbs="vm.breadcrumbs" wizard-pages="vm.wizardPages" current-page="vm.page"> 

...

</wizard>

这是未经测试的,但希望能给您带来启发。此外,如果隔离范围能够更改当前页面,那么您当然需要将其更新为双向绑定。