Angularjs 使用ngGrid中的afterSelectionChange将该点设置为null
我正在使用angular和typescript编写应用程序。Angularjs 使用ngGrid中的afterSelectionChange将该点设置为null,angularjs,typescript,this,ng-grid,Angularjs,Typescript,This,Ng Grid,我正在使用angular和typescript编写应用程序。 我正在使用ng网格,我必须处理afterSelectionChange事件。 我尝试用两种方式设置事件处理程序 this.$scope.settoriGridOptions.afterSelectionChange = this.afterSelectionChange; 其中this.afterSelectionChange是控制器类的方法, 及 包括内部代码,但在这两种情况下,此指针不正确,我无法访问控制器的服务。 我怎样才
我正在使用ng网格,我必须处理afterSelectionChange事件。 我尝试用两种方式设置事件处理程序
this.$scope.settoriGridOptions.afterSelectionChange = this.afterSelectionChange;
其中this.afterSelectionChange是控制器类的方法,及 包括内部代码,但在这两种情况下,此指针不正确,我无法访问控制器的服务。
我怎样才能解决这个问题 经过更多的测试和阅读一些文章后,我发现问题在于在函数调用中隐式传递这个指针作为参数 如果我写
$scope.filtroSoluzione = this.filtroSoluzione;
调用时,此指针设置为null,但如果我写入
$scope.filtroSoluzione = () => { return this.filtroSoluzione() };
或
$scope.filterosoluzione=()=>{..内联代码…}
此指针已正确设置。我怎样才能有更一致的行为?我不喜欢总是在里面写代码,因为这样会使类更难阅读和导航 谢谢,
卢卡谢谢你在编辑中提供的额外信息,我现在看到了问题所在
class foo {
public afterSelectionChange = () => {
console.log(this);
}
}
当您像上面那样声明函数时,您的this
是实例,而不是您所看到的,因为它捕获了this
变量。但它也有成本,因为现在它为类的每个实例创建了一个新的afterSelectionChange函数。在这种情况下,我认为这仍然是你想要的
var foo = (function () {
function foo() {
var _this = this;
this.afterSelectionChange = function () {
console.log(_this);
};
}
foo.prototype.baz = function () {
console.log(this);
};
return foo;
})();
在上面的代码生成器中,您可以看到使用name=()=>{}
和常规方法声明函数时的区别
另一种解决方案可能是:
this.$scope.settoriGridOptions.afterSelectionChange = this.afterSelectionChange.bind(this);
但我也不觉得这很好。。。(这应该适用于正常的
public afterSelectionChange(){}
声明您已经习惯了。我认为需要更多地查看您的代码。例如,我们需要了解为什么您需要使用this
访问$scope
…好的,谢谢。回到我不明白的问题,我是否以及如何克服这个问题,并使用方法作为事件处理程序,以获得更一致的行为r和更干净的代码。当您使用“public afterSelectionChange=()=>{}”声明它时,您可以使用它作为事件处理程序使用您拥有的代码(this.$scope.settoriGridOptions.afterSelectionChange=this.afterSelectionChange),并且如果需要,仍然可以使用它作为普通方法调用。afterSelectionChange()。你是对的,它与其他方法声明不一致,但没有一种好的方法(我知道)。我用其他解决方案编辑了上面的文章。谢谢,第二种解决方案更好,我的代码更干净
this.$scope.settoriGridOptions.afterSelectionChange = this.afterSelectionChange.bind(this);