【问题标题】:AngularJS Controller as syntax and DirectivesAngularJS 控制器作为语法和指令
【发布时间】:2014-10-02 01:59:30
【问题描述】:

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

我正在使用 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);

        });
    }
}

我将如何将客户传递给通常会继承父控制器的 $scope 的指令。

【问题讨论】:

    标签: angularjs typescript


    【解决方案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 controller 的实例会像这样被注入到$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;
    

    所以我们现在可以访问我们的控制器的任何公共内容。上述控制器 sn-p 的稍微简化(但精确)的版本:

    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
    

    【讨论】:

      猜你喜欢
      • 2014-05-05
      • 2014-07-27
      • 2014-02-12
      • 1970-01-01
      • 2013-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      相关资源
      最近更新 更多