In AngularJS .query()
and .get()
methods often used to retrieve data/response from server. Sometimes you have to use same method to get that information but in another controller/s. In this case you are actually affecting the performance. These same queries (called in different controllers) will always send request to the server and the app has to wait for the response.
Rule 1. Don’t call same query at multiple places.
angular.module('webDesignColors') .controller('FirstController', function (api, $scope) { api.query().$promise.then(function (result) { // Your stuff here }); })
.controller('SecondController', function (api, $scope) { api.query().$promise.then(function (result) { // Your stuff here }); });
As you can see that api.query()
is called twice in both controllers. So two HTTP requests will be made on server.
Rule 2. Scope variable is your friend!
We can avoid this behavior! AngularJS developers frequently use scope variables for function call or just as a variable. You can cache the query response in a scope variable and use it anywhere.
angular.module('module') .controller('FirstController', function (api, $scope) { $scope.queryData = api.query(); $scope.queryData.$promise.then(function (result) { // Your stuff here }); })
.controller('SecondController', function (api, $scope) { $scope.queryData.$promise.then(function (result) { // Your stuff here }); });
This will not only reduce HTTP requests but also boost the performance of your angular app 🙂
You might also like:
AngularJS learning and examples:
- Advanced search in AngularJS
- Basic search in AngularJS
- AngularJS in 20 minutes
- Angular column filter for Bootstrap
- AngularJS ‘mouseleave’ event : error and solution
jQuery plugins:
- jqExtension – jQuery file type validation plugin
- jQuery validation for file type extension
- jQuery validationEngine: Extended jQuery form validations
- jQuery Ad Gallery – Extended Photo Gallery Slideshow
- Simple and easy Cookie based jQuery tabs
- Simple jQuery Single Level Drop Down Menu
Leave a Reply