2017-10-01 9 views
0

私はhttpと呼ばれるサービスを持っています。問題は、コントローラで$ scope.photosを使用する方法を理解できないということです。これを行うにはコントローラとサービスを設定してください。サービスでhttpコールを発信するが、コントローラから応答を受け取るにはどうすればよいですか? AngularJS

app.service('http',function($scope,$http){ 
     function getAll() { 
     $http.get('/allphotos').then(function success(response) { 
      $scope.photos = response.data; 
     }, function error(err) { 
      console.log('error is:' + err.err) 
     }); 
    } 
}); 

    app.controller('ctrl',function ($scope, http) { 

} 

答えて

2

まず、サービス/工場/プロバイダ内で$scopeを使用しないでください。スコープはコントローラのみに関連しています。コントローラとのバインドビューを扱います。


あなたは約束を返す必要がありますし、あなたのコントローラ内部でそれを解決することができるようになります方法getAll()を持っています。

app.service('httpService',function(,$http){ 
     this.getAll = function() { 
     return $http.get('/allphotos').then(function(response) { 
     //^'getAll' returns Original Promis comes from '$http' 
      return response.data; 
     // ^here we resolve 'response.data' 
     }, function(err) { 
      console.log('error is:' + err.err) 
     }); 
    } 
}); 

そして今、コントローラでの操作を行います:

何かのように

app.controller('ctrl',function ($scope, httpService) { 
    httpService.getAll().then(function(data) { 
      $scope.data = data; 
     }, function error(err) { 
      console.log('error is:' + err.err) 
     }); 
} 
+0

おかげで、あなたは私をたくさん助けた:)ところで、私は変わっ '関数のgetAllを()' this.getAll」に! = function() 'それは仕事をしなかった – rebilliony

+0

@rebillionyはい、 'this.getAll = ...' –

関連する問題