2014-10-02 49 views
1

所以我一直在探索AngularJS中的Controller as语法,我想知道如何处理directives和$ scope,特别是继承控制器的$ scope或从一个子指令的属性。我使用的打字稿AngularJS控制器作为语法和指令

,所以给这个控制器:

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); 

     }); 
    } 
} 

我怎么会去传递顾客到一个指令,它通常会继承父控制器的$范围。

回答

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控制器的实例将被注入into $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); 
     ... 

我们认为(一次通过的$ HTTP加载)我们可以消耗上面这样的结果:

<div> 
    {{Events.customer}} // public propeties of this.$scope 
相关问题