我有一個控制器內的函數,我很困惑如何更新.then函數內的$ 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
我用$範圍$莫名其妙申請?
編輯:
這裏的上下文
(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變量傳遞給它。 – Noppey
由'then'調用的函數作爲不同的範圍。如果你使用的是ES6,你可以使用箭頭函數,或者當我不通過$ scope變量時使用'bind()' – rpadovani
,我在控制檯中得到以下錯誤:「ReferenceError:$ scope is not defined」 – Jcr