title: AngularJS: How do I get data from a server before changing routes
body: <p>Angular 1.3 question: I've read many Stack Overflow questions and tutorials but haven't been able to get my specific code working. I want to have a view with a button (page1.html). When the button is clicked, it will get data from the server and render it in a second view (page2.html).</p>
  
  <p>Here is the basic code:</p>
  
  <pre><code>var app = angular.module("app", ["ngRoute", "ngResource"]);
  
  app.config(["$routeProvider", function ($routeProvider) {
      var baseTemplatePath = "/static/templates/";
  
      $routeProvider
          .when("/", {
              templateUrl: baseTemplatePath + "page1.html",
              controller: mainController
              // Don't render the next route's template until data comes back
              // from the ng-click function on this view.
          })
          .when("/page2", {
              templateUrl: baseTemplatePath + "page2.html",
              controller: mainController,
              resolve: mainController.resolve
          })
          .otherwise({ redirectTo: "/" });
  }]);
  
  app.factory("mainFactory", ["$resource", function ($resource) {
      return $resource("/api/:arg1/:arg2", {}, {
          query: { method:"GET", params: { arg1: "somthing", arg2: "something-else" }}
      });
  }]);
  
  var mainController = app.controller("mainController", ["$scope", "mainFactory", "myData", function ($scope, mainFactory, myData) {
  
      // When user clicks a button, it should get the data and go to the next route.
      $scope.getData = function () {
          $scope.myData = this.resolve;
      };
  }]);
  
  mainController.resolve = {
      myData: function (mainFactory, $q) {
          var deferred = $q.defer();
          mainFactory.query(function (successData) {
              deferred.resolve(successData); 
          }, function (errorData) {
              deferred.reject();
          });
          return deferred.promise;
      },
      delay: function ($q, $defer) {
          var delay = $q.defer();
          $defer(delay.resolve, 1000);
          return delay.promise;
      }
  };
  </code></pre>
  
  <p>This is from the template with the <code>ng-click</code> on the link:</p>
  
  <pre><code>&lt;a class="btn btn-primary btn-lg" ng-click="getData()" href="#/page2"&gt;Start&lt;/a&gt;
  </code></pre>
  
  <p>The second view renders the data with <code>ng-repeat</code>.</p>
  
  <p>I've tried borrowing some code from <a href="https://stackoverflow.com/questions/11972026/delaying-angularjs-route-change-until-model-loaded-to-prevent-flicker">this question</a>, and don't understand exactly what I'm doing wrong. </p>