gpt4 book ai didi

javascript - 使用 bindToController 时,指令的范围变量在构造函数中未定义

转载 作者:搜寻专家 更新时间:2023-10-30 21:07:22 24 4
gpt4 key购买 nike

所以我有一个指令,它在创建时应该有一个值。让我们调用指令 MyDirective。要使用它并向它传递一个值,您可以这样做:

<my-directive value="'I will be undefined'"></my-directive>

我使用的是 TypeScript,所以我想要没有 $scope 的类,为此我绑定(bind)到 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 因为传递给指令的值(“我将是未定义的”)在构造函数中(我需要它的地方)还没有设置...)

有没有更好的方法在没有 watch 的情况下做到这一点?

最佳答案

a working example

我只是稍微调整了你的代码 - 它正在运行:

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()}])
}

关于javascript - 使用 bindToController 时,指令的范围变量在构造函数中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32993497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com