【发布时间】:2016-06-26 13:52:37
【问题描述】:
我在控制器中有一个函数,我对如何从 .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
我会以某种方式使用 $scope.$apply 吗?
编辑:
这是上下文的整个控制器
(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 变量传递给它。
-
then调用的函数作为不同的范围。如果你使用 ES6,你可以使用箭头函数,或者bind() -
当我没有传入 $scope 变量时,我在控制台中收到以下错误:“ReferenceError: $scope is not defined”
-
您是否在控制器中注入了 $scope 变量?
-
我要发布整个控制器
标签: javascript angularjs