I have successfully integrated Angular 1 and Angular 2 by creating an Angular 1 controller and service, along with an Angular 2 component. These components work seamlessly together for data retrieval and storage. Here is a snippet of my HTML page:
<body>
<h3>Angular 1 service</h3>
<div ng-controller="MainController">
<input ng-model="username" />
<button ng-click="setUser()">Set User</button>
<button ng-click="getUser()">Get User</button>
<div>User in service : {{user}}</div>
</div>
<hr>
<h3>Angular 2 component uses Angular 1 service</h3>
<user-section></user-section>
</body>
The MainController looks like this:
myApp.controller('MainController', function ($scope, UserService) {
$scope.getUsers = function () {
UserService.setUser($scope.username);
window.location = './angular2.html'
};
$scope.setUser = function () {
UserService.setUser($scope.username);
$scope.user = $scope.username;
};
$scope.getUser = function () {
$scope.user = UserService.getUser();
};
});
The UserService code is as follows:
function UserService(){
this.user = "default";
}
UserService.prototype.getUsers = function(){
var users = ['user1', 'user2', 'user3'];
return users;
}
UserService.prototype.setUser = function(usr){
this.user = usr;
}
UserService.prototype.getUser = function(){
return this.user;
}
And the Angular 2 component section:
import {Component, Inject} from 'angular2/core';
@Component({
selector: 'user-section',
templateUrl: '<div>
<input [(ngModel)]="username" />
<button (click)="setUser()">Set User</button>
<button (click)="getUser()">Get User</button>
<button (click)="getUsers()">Get Users</button>
<br/>
<ul>
<li *ngFor="#userId of users">{{userId}}</li>
</ul>
<div>User in service : {{user}}</div>
</div>'
})
export class UserSection {
constructor(@Inject('UserService') userService:UserService) {
this.users = [];
this.username = '';
this._UserService = userService;
}
getUsers(){
this.users = this._UserService.getUsers();
}
setUser(){
this._UserService.setUser(this.username);
}
getUser(){
this.user = this._UserService.getUser();
}
}
To update the Angular 2 model whenever the Angular 1 input changes, an event (getUser) must be fired consistently. You can check out a working example on Plunker here. If you want to make Angular 2 listen to changes in the Angular 1 service, there are listeners available in Angular 2 that can potentially serve this purpose, but the implementation might require further exploration.