var app = angular.module('app', []);
(function(app) {
function MyController() {
this.fname1 = 'RGFsdG9uDQo';
this.lname1 = 'RGhhdmFyZXYNCg';
this.addr1 = "UGFjaGFsYW0NCg";
}
MyController.prototype.get1 = function() {
return "Addr: " + this.addr1;
};
app.directive("ch", function() {
return {
restrict: 'E',
scope: {},
transclude: true,
bindToController: {
fname1: '@',
lname1: '=',
update1: '&'
},
controller: MyController,
controllerAs: 'ctrl',
template: ['<input ng-model="ctrl.fname1">',
'<input ng-model="ctrl.lname1">',
'<input ng-model="ctrl.addr1" ng-change="ctrl.update1({addr: ctrl.get1()})">'
].join('')
};
});
})(app);
(function(app) {
function MyController() {
this.fname2 = 'RGFsdG9uDQo';
this.lname2 = 'RGhhdmFyZXYNCg';
this.addr2 = "UGFjaGFsYW0NCg";
}
MyController.prototype.update2 = function(addr) {
this.addr2 = addr;
};
MyController.prototype.get2 = function() {
return "FName: " + this.fname2;
};
app.directive("pr", function() {
return {
restrict: 'E',
scope: {},
transclude: true,
bindToController: {},
controller: MyController,
controllerAs: 'ctrl',
template: ['<input ng-model="ctrl.fname2">',
'<input ng-model="ctrl.lname2">',
'<input ng-model="ctrl.addr2">',
'<br /><br />',
'<ch fname1="{{ctrl.get2()}}" lname1="ctrl.lname2" update1="ctrl.update2(addr)"></ch>',
'	',
'<ch fname1="{{ctrl.get2()}}" lname1="ctrl.lname2" update1="ctrl.update2(addr)"></ch>'
].join('')
};
});
})(app);
<html ng-app="app">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Angular 1</title>
<script src="https://code.angularjs.org/1.5.0-rc.1/angular.min.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<pr></pr>
</body>
</html>
如何使用打字稿语言将this code转换为angular2组件。 这是使用bindToController的示例代码。 有一个父指令。 在此之下,还有一些其他指令(他们的孩子)。 它有范围@,&amp;和=。
答案 0 :(得分:0)
我会创建两个组件。一个用于ch
指令:
import {Component,Input,Output} from 'angular2/core';
@Component({
selector: 'ch',
template: `
<input [(ngModel)]="fname1">
<input [(ngModel)]="lname1">
<input [(ngModel)]="addr1" (change)="update1()">
`
})
export class ChComponent {
@Input() fname1:string;
@Input() lname1:string;
@Input() addr1:string;
@Output('update1') update1Event;
constructor() {
this.fname1 = 'RGFsdG9uDQo';
this.lname1 = 'RGhhdmFyZXYNCg';
this.addr1 = "UGFjaGFsYW0NCg";
this.update1Event = new EventEmitter();
}
update1() {
update1Event.emit(this.addr1);
}
}
一个用于pr
指令:
import {Component,Input,Output} from 'angular2/core';
import {ChComponent} from './ch.component';
@Component({
selector: 'pr',
template: `
<input [(ngModel)]="fname2">
<input [(ngModel)]="lname2">
<input [(ngModel)]="addr2">
<br /><br />
<ch [fname1]="fname2" [lname1]="lname2"
(update1)="update2($event)"></ch>
	
<ch [fname1]="fname2" [lname1]="lname2"
(update1)="update2($event)"></ch>
`,
directives: [ ChComponent ]
})
export class PrComponent {
constructor() {
this.fname2 = 'RGFsdG9uDQo';
this.lname2 = 'RGhhdmFyZXYNCg';
this.addr2 = "UGFjaGFsYW0NCg";
}
update2() {
this.addr2 = this.addr2 + "1";
}
}
修改强>
发表评论后,有以下详细信息:
主页它可以帮到你, 亨利