所以我一直在研究AngularJS中的Controller as
语法,我想知道如何处理directives
和$ scope,特别是从子指令继承控制器$ scope或properties。
我正在使用Typescript,所以给这个控制器:
export class DefaultController implements IDefaultController {
customer: Models.ICustomer;
static $inject = ['$scope', 'config', 'customerDataService'];
constructor(private $scope: ng.IScope, private config: ApplicationConfig, private customerDataService: Services.ICustomerDataService) {
}
getCustomerById(id: number): void {
console.log(this.config.version);
this.customerDataService.getCustomer(id).then((customer) => {
this.customer = angular.extend(new Models.Customer(), customer);
});
}
}
我如何将客户传递给通常会继承父控制器$范围的指令。
答案 0 :(得分:1)
如果我们宣布as
这样(inside of a View)
:
<div ng-controller="DefaultController as Events">
...
指令def几乎相同:
export class MyDefaultDirective implements ng.IDirective
{
public restrict: string = "E";
public replace: boolean = true;
...
public controller: string = "DefaultController as Events";
...
我们可以预期,this
控制器的实例将被注入$scope
,如下所示:
// this was done by angular
// - the 'as' part was used for a property name
// - current controller instance was injected
var controller = this.$scope.Events;
因此,我们现在可以访问控制器的任何公共内容。以上控制器片段的简化(但确切)版本:
export class DefaultController implements IDefaultController {
// explicit public just to show that this will be available
public customer: Models.ICustomer;
....
getCustomerById(id: number): void {
this.customerDataService.getCustomer(id).then((customer) => {
// HERE
// this.$scope.Events.customer is ready for use
this.customer = angular.extend(new Models.Customer(), customer);
...
在我们的View (一旦通过$ http加载),我们可以使用以上结果:
<div>
{{Events.customer}} // public propeties of this.$scope