user6018902 user6018902 - 1 month ago 6
JSON Question

How to use a json file with a single controller app in AngularJS

I don't know how to make a service for a json file and call this service in my controller.
I have one controller in my app,and so must remain.

Answer

Try to run this example via run code snippet blue button.

Basically, You need to declare that service, the require it via Angular.DI, lastly call the service method and wait for its result. Hope it helps

angular
  .module('test', [])
  .constant('API' , 'https://jsonplaceholder.typicode.com')
  .service('TestService', function(API, $http) {
      
    this.getData = function() {
      return $http
        .get(API + '/photos')
        .then(function(response) {
          return response.data;
        })
      };
  })
  .controller('TestCtrl', function($scope, TestService) {
  
  //But a Resolve is preferred
  TestService
    .getData()
    .then(function(data) {
      $scope.album = data;
    })
  ;
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<section ng-app="test">
  <article ng-controller="TestCtrl">
    <div ng-repeat="photo in album">
      <h3 ng-bind="photo.title"></h3>
      <img ng-src="{{photo.thumbnailUrl}}" />
    </div>
  </article>
</section>

Comments