gpt4 book ai didi

javascript - Angular JS 使用 controllerAs 和带有作用域或 this 变量的语法

转载 作者:行者123 更新时间:2023-12-03 07:37:29 25 4
gpt4 key购买 nike

我经常遇到一个问题,它导致与 Controller 作用域变量的定义不一致。

您可能知道,使用 controllerAs 语法,您必须将所有变量与 Controller 函数 内的 this 实例附加在一起,如下所示:

angular.module('angularJsInternationalizationApp')
.controller('MainCtrl', function (SampleService) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];

this.translatedFromService = '';
SampleService.getTranslation().then(function(data){
this.translatedFromService = data;
});
});

现在的问题是 this.translatefDromService 无法从任何服务的成功错误功能进行更新,或者事实上任何服务其他函数,因为它将其作为新函数的实例而不是 Controller 。

在这种情况下可以做什么。

我使用了一种解决方案,将其标记为 vm。var vm = this 在 Controller 的开头,但除此之外还有什么解决方案吗?

干杯!

最佳答案

您有 2 个选择:

1) 使用 vm = this 方法,保留 Controller 的 this 上下文的链接:

angular.module('angularJsInternationalizationApp')
.controller('MainCtrl', function (SampleService) {
var vm = this;
vm.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];

vm.translatedFromService = '';
SampleService.getTranslation().then(function(data){
vm.translatedFromService = data;
});
});

2) 使用bind() method在处理程序上,这会将调用函数的上下文修改为 Controller 的 this:

angular.module('angularJsInternationalizationApp')
.controller('MainCtrl', function (SampleService) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];

this.translatedFromService = '';
SampleService.getTranslation().then(function(data){
this.translatedFromService = data;
}.bind(this));
});

关于javascript - Angular JS 使用 controllerAs 和带有作用域或 this 变量的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35547815/

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