gpt4 book ai didi

javascript - Controller 声明中的 Angular Meteor 箭头函数

转载 作者:行者123 更新时间:2023-11-27 23:33:28 26 4
gpt4 key购买 nike

我正在关注this Angular-Meteor tutorial 。还有这样的代码片段:

angular.module('socially').directive('partiesList', function () {

return {
restrict: 'E',
templateUrl: 'parties-list.html',
controllerAs: 'partiesList',
controller: function ($scope, $reactive) {
$reactive(this).attach($scope);

this.newParty = {};

this.helpers({
parties: () => {
return Parties.find();
}
});

this.addParty = () => {
Parties.insert(this.newParty);
this.newParty = {};
};

this.removeParty = (party) => {
Parties.remove({_id: party._id});
};
}
};
});

我主要关心 () => {} 语法。如果我在 Controller 声明中使用箭头函数语法,它将不起作用:

...
controller: ($scope, $reactive) => { //this does not work
$reactive(this).attach($scope);

this.newParty = {};

this.helpers({
parties: () => {
return Parties.find();
}
});
...

有人可以解释一下什么时候可以使用箭头函数,什么时候不能使用吗?

最佳答案

它不起作用,因为箭头函数不会像常规函数那样创建新的 this 上下文,而是使用父函数的上下文。当定义 Controller 时,它很重要,而当定义助手时,它则不重要。如需更详细的答案,您还可以查看这里:https://github.com/Urigo/angular-meteor/issues/965#issuecomment-165916592

关于javascript - Controller 声明中的 Angular Meteor 箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34338692/

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