【发布时间】:2016-01-04 18:14:03
【问题描述】:
所以我有一个指令,它在创建时应该取一个值。我们将指令称为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,因为在构造函数中(我需要它...)时,传递给指令的值(“我将未定义”)尚未设置。
有没有更好的不带手表的方法?
【问题讨论】:
-
我认为您将
controllerAs与bindToController混淆了。 ControllerAs 只是将控制器作为变量分配给范围。其中,bindToController 将使用控制器作为范围。所以this === $scope是真的。 -
这可能是,我只是想使用没有
$scope变量的类,并将一个值传递给我可以在没有手表的情况下使用的指令,知道是否可以这样做吗?
标签: javascript angularjs angularjs-directive typescript