所以我有一个指令,在创建时应该取一个值。让我们将指令称为MyDirective。要使用它并将值传递给它,您可以这样:
MyDirective
<my-directive value="'I will be undefined'"></my-directive>
我正在使用TypeScript,所以我想拥有没有类的类$scope,因此我将其绑定到控制器。
$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因为在构造函数中(我需要的地方……)传递给指令的值(“我将是未定义的”)尚未设置。
$watch
有没有更好的方法可以做到这一点而无需监视?
有一个可行的例子
我只是稍微调整了一下代码-即可正常工作:
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()}]) }