使用bindToController

时间:2015-10-07 13:27:44

标签: javascript angularjs angularjs-directive typescript

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

有没有更好的方法可以在没有手表的情况下做到这一点?

1 个答案:

答案 0 :(得分:4)

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