title: Ways of loading data into controller via service in AngularJS
body: <p>I have a service that loads data using $http and returns a promise (simplified for brevity):</p>
  
  <pre><code>angular.module('myApp').factory('DataService', ['$http', function($http) {
    function unwrapFriendList(data) {
      ...
      return unwrappedFriendList;
    }
  
    return {
      getFriendList: function() {
        return $http.get('/api/friends').then(unwrapFriendList);
      }
    }
  }]);
  </code></pre>
  
  <p>Here is a view that uses that data, after promise is resolved and result is stored in <code>$scope.friends</code>:</p>
  
  <pre><code>&lt;div ng-repeat='friend in friends'&gt;
    {{friend.firstName}} {{friend.lastName}}
  &lt;/div&gt;
  </code></pre>
  
  <p>When it comes to loading that data into the controller, I've come across a couple of ways to do that.</p>
  
  <h2>Option 1: Controller that uses data loaded via ng-route <code>resolve</code></h2>
  
  <pre><code>angular.module('myApp').controller('FriendListCtrl', ['$scope', 'friendList', function($scope, friendList) {
    $scope.friends = friendList;
  }]);
  </code></pre>
  
  <p>Route section:</p>
  
  <pre><code>angular.module('myApp', ...).config(function($routeProvider) {
    $routeProvider
      .when('/friends', {
        templateUrl: 'views/friends.html',
        controller: 'FriendListCtrl',
        resolve: {
          friendList: ['DataService', function(DataService) {
            return DataService.getFriendList();
          }]
        }
      })
      ...
  });
  </code></pre>
  
  <h2>Option 2: Controller that triggers data loading by itself</h2>
  
  <pre><code>angular.module('myApp').controller('FriendListCtrl', ['$scope', 'DataService', function($scope, DataService) {
    DataService.getFriendList().then(function(friendList) {
      $scope.friends = friendList;
    });
  }]);
  </code></pre>
  
  <hr>
  
  <h2>Questions</h2>
  
  <ul>
  <li>Are there other commonly used ways of doing this? If so, please illustrate with a code example.</li>
  <li>What are the limitations of each approach?</li>
  <li>What are advantages of each approach?</li>
  <li>Under what circumstances should I use each approach?</li>
  </ul>