Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use AngularJS (Angular1) module from Angular2 project

Just started a demo Angular2 project (no previous experience with Angular1/AngularJS. Have followed and extended from the online quickstart and tutorials, and all was fine. However I'm at the point where I would like to use some components from a library which is designed for AngularJS, and having no end of problems!

Most of the information available about AngularJS/Angular2 compatibility assumes that you have an AngularJS project that you're adding Angular2 components to - not the other way around - so what I'm hoping to do may not even be possible. What I've tried so far involves a simple stripped-back project based on the Angular2 quickstart, with a single Angular2 component that loads into the index.html. I'd then like to integrate components from the existing library (AngularJS-based) into this.

  • I've tried using UpgradeAdapter.upgradeNg1Component to create components from the library and add them directly into my Angular2 component

  • I've tried installing angularjs through npm, importing it in a script tag into my index.html and then using a combination of UpgradeAdapter.downgradeNg2Component and UpgradeAdapter.bootstrap to load my Angular2 as a downgraded module

Neither of these seem to work - the component fails to show, and the browser console tells me I've got an Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/angular2/upgrade Error loading http://localhost:3000/app/main.js

My best guess at the moment is that this is actually an unsupported scenario, and I need to have a 'proper' AngularJS app in order to use the UpgradeAdapter functionality from Angular2. Can anyone confirm this? Or is there something stupid I'm missing here?

like image 834
Michael Avatar asked Feb 06 '16 04:02

Michael


2 Answers

Here is a working plunkr describing how to mix Angular1 and Angular2 elements:

  • http://plnkr.co/edit/yMjghOFhFWuY8G1fVIEg?p=preview

An important point is to bootstrap your main component on the UpgradeAdapter. This way all elements are available in providers (services / factories) and in directives (components / directives):

upgrade.bootstrap(document.body, ['heroApp']);

These two answers could help you:

  • angular 1.x and angular2 together
  • How to inject upgraded Angular 1 service/factory to Angular 2 component in ES5?
like image 174
Thierry Templier Avatar answered Nov 10 '22 03:11

Thierry Templier


So the major problem in this case turned out to be the fact that it appears that the upgrade components aren't included as part of the basic angular 2 bundle. After adding:

<script src="node_modules/angular2/bundles/upgrade.min.js"></script>

to my index.html file the error I was seeing disappeared.

Thanks to the answer here for pointing me in the right direction!

like image 21
Michael Avatar answered Nov 10 '22 04:11

Michael