一尘不染

使用bindToController时,构造函数中未定义指令的作用域变量

angularjs

所以我有一个指令,在创建时应该取一个值。让我们将指令称为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因为在构造函数中(我需要的地方……)传递给指令的值(“我将是未定义的”)尚未设置。

有没有更好的方法可以做到这一点而无需监视?


阅读 180

收藏
2020-07-04

共1个答案

一尘不染

一个可行的例子

我只是稍微调整了一下代码-即可正常工作:

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()}])
}
2020-07-04