更新$ scope里面.then?

时间:2016-06-26 13:52:37

标签: javascript angularjs

我在控制器中有一个函数,我对如何从.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。$以某种方式申请?

编辑:

这里是整个上下文控制器

(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);

})();

3 个答案:

答案 0 :(得分:2)

保存对$ 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:只有当您想要更改$scope之外的$digest时才需要它,例如当您使用外部(非角度)库/函数时, WebSocket或jquery事件侦听器。直到Spotify是一个有角度的服务/工厂 - 您不需要$scope.$apply

来自docs

  

$ apply()用于从角度框架外部以角度执行表达式。 (例如,来自浏览器DOM事件,setTimeout,XHR或第三方库)。

答案 1 :(得分:1)

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

应该是你真正需要的。您基本上是在告诉内部范围this应该是什么

答案 2 :(得分:1)

你应该使用

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