【发布时间】:2017-05-25 20:41:34
【问题描述】:
我将角度 1 和角度 2 整合在一起。因此,我有 angular 1 控制器和服务以及 angular 2 组件。这些对于数据检索和存储都可以正常工作,反之亦然。下面是我的html页面。
<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>
控制器如下,
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();
};
});
服务如下,
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;
}
角度2分量如下,
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();
}
}
需要始终为角度 2 触发事件(getUser)以从角度 1 中获取名称。工作 plunker https://plnkr.co/edit/fYbIeJUUY7Xst7GEoi2v?p=preview 每当更改 angular 1 输入时,我想更新 angular 2 模型。有没有办法做到这一点? angular 2 中有听众,但我不知道如何让他们收听 angular 1 服务。
【问题讨论】:
标签: angularjs angular typescript integration