Delaying AngularJS Route Change Until Model Loaded to Prevent Flicker
AngularJS provides a convenient way to manage routing in web applications. However, there are scenarios where you may want to delay showing a new route until after the corresponding models and data have been loaded from the server. This can be useful to prevent flickering or blank page displays while the data is being retrieved.
The $routeProvider.Resolve Property
The $routeProvider.resolve property allows you to specify dependencies that need to be resolved before a route change can occur. This means that the route change will be delayed until these dependencies have been met.
Defining a Route with Resolve
To define a route that delays the route change until the model has been loaded, simply specify the resolve property on the route configuration. For example:
$routeProvider.when('/projects', { templateUrl: 'partials/project-list.html', controller: PhoneListCtrl, resolve: PhoneListCtrl.resolve });
Implementing the Resolve Function
The resolve function is responsible for returning a promise. The route change will not proceed until this promise is resolved. Here is an example of a resolve function that retrieves a list of projects using the $resource service:
PhoneListCtrl.resolve = { phones: function (Phone, $q) { // Create a deferred object to resolve the promise later var deferred = $q.defer(); // Fetch the projects using $resource and resolve the promise when successful Phone.query(function (successData) { deferred.resolve(successData); }, function (errorData) { deferred.reject(); // Optionally pass error data here }); // Return the promise return deferred.promise; }, // For demonstration purposes, add a delay to the resolve delay: function ($q, $defer) { var delay = $q.defer(); $defer(delay.resolve, 1000); return delay.promise; } };
Once the resolve function is complete, the corresponding controller can access the resolved data, such as the list of projects.
Prevent Flickering While Loading Data
While the data is being loaded, you can prevent flickering by continuing to display the current page. This can be achieved by using the ng-switch directive to conditionally display the loading state or the loaded data.
Demo and Source Code
For a working example and source code, please refer to:
The above is the detailed content of How to Prevent AngularJS Route Change Flickering by Delaying Until Model Loads?. For more information, please follow other related articles on the PHP Chinese website!