The way you do this is great (I prefer to use state = 'loading' and keep things a little more flexible.)
Another way to solve this problem are the promises and $routeProvider resolve properties. Using this delays the execution of the controller until a set of specified promises is allowed, for example. Data uploaded through resource services is ready and correct. Tabs in Gmail work the same way, i.e. you are not redirected to a new view, unless the data has been received from the server successfully. In case of errors, you remain in the same view or redirected to the page with an error, not the view that you tried to load and failed.
You can configure routes as follows:
angular.module('app', []) .config([ '$routeProvider', function($routeProvider){ $routeProvider.when('/test',{ templateUrl: 'partials/test.html' controller: TestCtrl, resolve: TestCtrl.resolve }) } ])
And your controller is like this:
TestCtrl = function ($scope, data) { $scope.data = data; // returned from resolve } TestCtrl.resolve = { data: function ($q, DataService){ var d = $q.defer(); var onOK = function(res){ d.resolve(res); }; var onError = function(res){ d.reject() }; DataService.query(onOK, onError); return d.promise; } }
References:
- Resolve
- Ahh! Just found a great (but surprisingly similar) explanation of the SO problem HERE
source share