对于指令范围的变量使用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>
我使用的是打字稿,所以我想有没有班 $范围
,所以我绑定到控制器。
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();
}
}
所以,问题是,我需要在使用 $腕表
因为传递的指令(我是不确定的),该值将尚未设置时构造函数(在我需要它...)
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?
推荐答案
我只是调整你的code位 - 这是工作:
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屋!