在一个控制器内共享2个函数之间的$ scope

时间:2014-12-06 09:38:19

标签: javascript angularjs

app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){

    $scope.ionLoader = true;

    getTopicContent.request($stateParams.topicId).then(function(response){
        $scope.threadContent = response.data;

    }).finally(function(){
        $scope.ionLoader = false;
    });


    $scope.loadPages = function ($scope) {
        if(totalPages > 1){
                $http({
                url: "http://someurl.php",
                method: "GET",
                params: {topicId: $stateParams.topicId,page : 2}
            }).success(function(data){
                 $scope.threadContent.push(data);
            });
        }
    }


}]);

我收到一个错误,说未定义的推送。 loadPages仅在用户滚动到页面底部时触发,因此我不认为它是异步问题,可能是$ scope问题? getTopicContent是我的服务。

1 个答案:

答案 0 :(得分:0)

您可以使用promise进行异步工作,并在loadPages中删除参数$ scope,如下所示:

app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){

    $scope.ionLoader = true;

    var promise = getTopicContent.request($stateParams.topicId).then(function(response){
        $scope.threadContent = response.data;

    }).finally(function(){
        $scope.ionLoader = false;
    });


    $scope.loadPages = function() {
        if(totalPages > 1){
                $http({
                url: "http://someurl.php",
                method: "GET",
                params: {topicId: $stateParams.topicId,page : 2}
            }).success(function(data){
                 promise.then(function(none) { 
                    $scope.threadContent.push(data); 
                 });
            });
        }
    }
}]);