【问题标题】:Scope variable for directive is undefined in constructor when using bindToController使用 bindToController 时,构造函数中未定义指令的范围变量
【发布时间】:2016-01-04 18:14:03
【问题描述】:

所以我有一个指令,它在创建时应该取一个值。我们将指令称为MyDirective。要使用它并向其传递值,您可以这样做:

<my-directive value="'I will be undefined'"></my-directive>

我正在使用 TypeScript,所以我希望有没有 $scope 的类,因此我绑定到控制器。

class MyDirectiveController {
    public value:string;

    constructor(private $scope: ng.IScope) {
        // I wanna do something with this.value at this point
        // But it is undefined ...
        console.log(this.value);

        $scope.$watch('value', this.valueDidChangeCallback).bind(this);

    }

    valueDidChangeCallback:any = () => {
        // Now I can do the thing I wanted to do ...
        console.log(this.value);
    };
}

export class MyDirectiveDirective {
    restrict: string = 'E';
    templateUrl: string = 'my-directive.html';
    bindToController: boolean = true;
    controllerAs: string = 'vm';
    scope:any = {
        'value': '='
    };

    controller: any = ($scope: ng.IScope) => new MyDirectiveController($scope);

    constructor() {}

    static Factory(): ng.IDirective {
        return new LicenseOverviewPageDirective();
    }
}

所以问题是我需要使用$watch,因为在构造函数中(我需要它...)时,传递给指令的值(“我将未定义”)尚未设置。

有没有更好的不带手表的方法?

【问题讨论】:

  • 我认为您将controllerAsbindToController 混淆了。 ControllerAs 只是将控制器作为变量分配给范围。其中,bindToController 将使用控制器作为范围。所以this === $scope 是真的。
  • 这可能是,我只是想使用没有$scope 变量的类,并将一个值传递给我可以在没有手表的情况下使用的指令,知道是否可以这样做吗?

标签: javascript angularjs angularjs-directive typescript


【解决方案1】:

a working example

我刚刚稍微调整了您的代码 - 它正在工作:

namespace MyNamespace { 

    export class MyDirectiveController {
        public value:string;    
        static $inject = ['$scope'];

        constructor(private $scope: ng.IScope) {
            // I wanna do something with this.value at this point
            // NOW It is defined
            console.log(this.value);
            $scope.$watch('value', this.valueDidChangeCallback).bind(this);
        }

        valueDidChangeCallback:any = () => {        
            // Now I can do the thing I wanted to do ...
            console.log(this.value);
        };
      }

    export class MyDirectiveDirective {
        restrict: string = 'E';
        templateUrl: string = 'my-directive.html';
          controller = MyNamespace.MyDirectiveController;
          controllerAs: string = 'vm';
        bindToController: boolean = true;    
        scope:any = {
            'value': '='
        };
      }

    angular
       .module('MyApp')
       .directive('myDirective', [() => {return new MyNamespace.MyDirectiveDirective()}])
}

【讨论】:

  • 很高兴看到这一点!使用 Angular 享受 Typescript ;)
猜你喜欢
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多