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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…