我正在尝试使用 Angular 1 和 2 制作一个混合 Angular 应用程序。我有一个简单的 Angular 1 指令:
var sample = angular.module('interestApp',[]);
sample.directive('myComp', function() {
return {
scope:{},
restrict: 'E',
template: '<div>My name is </div>'
}
});
我想在我的 Angular 2 应用程序中使用此指令。所以我使用 UpgradeNg1Component() 对其进行转换,如下所示:
const upgradeAdapter: UpgradeAdapter = new UpgradeAdapter();
upgradeAdapter.bootstrap(document.body, ['interestApp']);
@Component({
selector: 'angular2',
template: '<myComp></myComp>',
directives: [upgradeAdapter.upgradeNg1Component('myComp')]
})
当我运行它时,我收到此错误:
EXCEPTION: No provider for $scope! (function (scope, elementRef)
谁能帮忙解决这个问题吗?或者,如果有人知道在 Angular 2 应用程序中使用 Angular 1 指令的任何其他方式,那将非常有帮助。
最佳答案
到目前为止,您的代码看起来不错,但似乎缺少一个部分。当您升级 ng1 组件以通过选择器 angular2 在 Angular 2 组件中使用它(我建议更改)时,您不会再次降级该 Angular 2 组件以实际在您的应用程序中使用它。引导 Angular 1 应用程序。
只要您在升级应用程序,这就是您始终必须做的事情。为了实例化 Angular 2 组件,您需要在 A1 中将其用作指令,因此需要将其降级。所以你需要做某事。像:
@Component({
selector: 'my-ng2-component',
template: '<myComp></myComp>',
directives: [upgradeAdapter.upgradeNg1Component('myComp')]
})
class MyNg2Component {
}
angular.module('interestApp', [])
.directive('myComponent', {...})
.directive('myNg2Component', upgradeAdapter.downgradeNg2Component(MyNg2Component);
upgradeAdapter.bootstrap(document.body, ['interestApp']);
完成升级后,您可以删除所有 Angular 1 特定部分和降级机制。
关于javascript - 无法使用 updateNg1Component() 在 Angular 2 应用程序中使用 Angular 1 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34864545/