使用 bindToController 时,在构造函数中未定义指令的范围变量 [英] Scope variable for directive is undefined in constructor when using bindToController
问题描述
所以我有一个指令,它在创建时应该取一个值.让我们调用指令 MyDirective
.要使用它并向其传递值,您可以这样做:
So I've got a directive which should take a value when created. Let's call the directive MyDirective
. To use it and pass a value to it you can do like this:
<my-directive value="'I will be undefined'"></my-directive>
我使用的是 TypeScript,所以我想要没有 $scope
的类,因此我绑定到控制器.
I'm using TypeScript so I want to have classes without $scope
, so for that I bind to controller.
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
因为传递给指令的值(I will be undefined")在构造函数中(我需要它的地方)还没有设置...)
So the problem is that I need to use $watch
because the value passed to the directive ("I will be undefined") will not yet be set when in the constructor (where I need it ...)
有没有更好的方法可以不用手表来做到这一点?
Is there a better way to do this without watch?
推荐答案
我只是稍微调整了您的代码 - 它正在工作:
I just adjusted your code a bit - and it is working:
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()}])
}
这篇关于使用 bindToController 时,在构造函数中未定义指令的范围变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!