Cmak Mak
Cmak Mak

Reputation: 21

angular page data loaded before rendering

I am new to Angular so my question might sound stupid to savvy Angular developers.

The big selling point of angular is data encapsulation for easy maintenance. Page's data need to be loaded before view is rendered. From documentation, I suppose we use resolve structure in routing configuration with $q.promise to achieve it. Well, for that to happen, I need to inject my controller, data service module or my data model into the app.config. Unfortunately, config does not allow injection (according to documentation). So I am stuck.

My next attempt is to attached a event handler for beforeRoutingChange (something like that) to do the loading. I don't like this approach, but seem the only thing working if I insist on data encapsulation - controller or model object controls the loading.

Is there a better way? Should the Angular controller provide a callback for loading data?

Upvotes: 2

Views: 1485

Answers (1)

John Munsch
John Munsch

Reputation: 19528

First off, let me correct a small misconception there. There is nothing in AngularJS that requires the page's data to load before a first rendering. It would be nice, but the bindings in your HTML can usually deal with there not being data on the scope for display at first. So you can always load to an "empty" page and have it fill in after service calls load data and put it into the $scope.

But beyond that, let me point you to a series of three short videos over on Egghead.io that should help you get this exactly the way you want it: https://egghead.io/search?q=resolve

Watch videos 35, 36, and 37 on that page. Total time for all three will be under 15 minutes of your time, but it should make it pretty clear how to perform the resolve you want to do. You should be able to inject $http into the function the same way he injects $timeout and you can make the call you want to make to get the initial data. Video #37 is a really good one because it covers the error handling case of what to do when something goes wrong with your service call and you don't want to show the end user a nice blank page.

Upvotes: 1

Related Questions