Angular UpgradeComponent找不到$ scope

时间:2017-09-01 22:43:58

标签: angularjs angular angular-upgrade

我有一个混合的角度cli,大致跟随Victor Savkin的Lazy Loaded AngularJS guide。 AngularJS在LazyLoaded Angular模块的构造函数中引导。我的应用程序和指南之间的主要区别在于我试图将<ui-view>指令包含在一些Angular组件中。由于我的布局结构如何,当AngularJS被引导时,<ui-view>元素将不可用,并且可以随时添加或删除。

import { Component, Directive, ElementRef, Injector } from '@angular/core';
import { UpgradeComponent } from '@angular/upgrade/static';
import * as angular from 'angular';

@Component({
  template: `
  <layout-wrapper>
    <my-toolbar></my-toolbar>
    <layout-contents>
      <ng2-ui-view>
        <h3 class="text-center">AngularJS page not loaded</h3>
      </ng2-ui-view>
    </layout-contents>
  </layout-wrapper>
  `,
})
export class LegacyOutputComponent { }

@Directive({selector: 'ng2-ui-view'})
export class UpgradedUiViewComponent extends UpgradeComponent {
  constructor(ref: ElementRef, inj: Injector) {
    super('uiViewWrapper', ref, inj);
  }
}

export const routerPatchModule = 'arcs.router.patch';

// We need to define a wrapper for ui-view because we can only upgrade
// components with only one definition. uiView cannot be automatically
// upgraded because its definition is too complex
angular.module(routerPatchModule, ['ui.router'])
.component('uiViewWrapper', { template: '<ui-view></ui-view>'})

当我运行代码时,会抛出Error: No provider for $scope!错误。检查堆栈跟踪我可以看到它被抛出UpgradeComponent超类。进样器尝试获取$scope

2 个答案:

答案 0 :(得分:1)

此设置无效。 AngularJS需要能够在应用程序的根目录中加载,以便正确定义范围。

解决此问题的更好方法是在应用程序的根目录中使用<div ui-view>指令(如在升级指南中),然后将布局组件从Angular降级为AngularJS以包装您的内容。 / p>

答案 1 :(得分:1)

替代方法是让Angular知道它需要提供$scope

import { Injector } from '@angular/core';

// allow $scope to be provided to ng1
export const ScopeProvider = {
  deps: ['$injector'],
  provide: '$scope',
  useFactory: (injector: Injector) => injector.get('$rootScope').$new(),
};

@Directive({
  providers: [ ScopeProvider ],
  selector: 'ng2-ui-view',
})
export class UpgradedUiViewComponent extends UpgradeComponent {
  constructor(ref: ElementRef, inj: Injector) {
    super('uiViewWrapper', ref, inj);
  }
}