gpt4 book ai didi

javascript - 更新 .then 内的 $scope 吗?

转载 作者:行者123 更新时间:2023-11-28 15:08:01 25 4
gpt4 key购买 nike

我在 Controller 中有一个函数,但我对如何从 .t​​hen 函数内部更新 $scope 变量感到困惑。

这是我的功能:

searchSpotify(query, $scope) {
this.Spotify.search(query,'track').then(function (data) {
console.log(data.tracks.items); // this is working
$scope.result = data;
});
}

在控制台日志中我收到此错误:

TypeError: Cannot set property 'result' of undefined

我是否以某种方式使用$scope.$apply?

编辑:

这是上下文的整个 Controller

(function() {

class SelectionController {
constructor(User, groupService, selectionService, songService, $scope, $routeParams, Spotify) {
this.groupId = $routeParams.groupId;
this.selectionId = $routeParams.selectionId;
this.groupService = groupService;
this.selectionService = selectionService
//this.selections = this.selectionService.getSelections();
this.songService = songService;
this.searchResults;
this.$scope = $scope;
this.Spotify = Spotify
}

searchSpotify(query) {
this.Spotify.search(query, 'track').then(function(data) {
console.log(data.tracks.items);
$scope.result = data;
});
}

addSong(name, artist, album) {
alert('called from selection controller');
this.songService.addSong(this.selectionId, name, artist, album);
}

createSelection(name, description) {
this.selectionService.createSelection(this.groupId, name, description);
}

deleteSelection(selection) {
this.selectionService.deleteSelection(selection);
}
}

angular.module('songSelectionApp')
.controller('SelectionController', SelectionController);

})();

最佳答案

保存对$scope的引用:

    searchSpotify(query) {
var $scope = this.$scope;
this.Spotify.search(query, 'track').then(function(data) {
console.log(data.tracks.items);
$scope.result = data;
});
}

或者使用arrow functions :

    searchSpotify(query) {
this.Spotify.search(query, 'track').then((data) => {
console.log(data.tracks.items);
this.$scope.result = data;
});
}

.bind(this) 也应该有效,正如另一个答案所建议的那样。

关于$scope.$apply:只有当您想要更改$digest之外的$scope时才需要它,例如例如,当您使用外部(非 Angular )库/函数时,例如 WebSocket 或 jquery 事件监听器。直到 Spotify 成为一个 Angular 服务/工厂 - 你不需要 $scope.$apply

来自docs :

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

关于javascript - 更新 .then 内的 $scope 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039164/

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