Reputation: 1298
Inside my Controller I have tried to stop $http being called multiple times, but my efforts seem to be in vein.
I only want the report's items to be loaded once.
Have tried checking for items being undefined and having a timesrun variable at the top of the Controller and increasing by 1 at the bottom of it.
if ($scope.items === undefined && $scope.timesrun == 0)
{
var req = {
method: 'GET',
*snipped*
};
$http(req).success(function (data, status, headers, config) {
$scope.items = data;
}).error(function (data, status, headers, config) {
SweetAlert.swal("Error " + status, data, "error");
});
}
I have even had this in a service but the service just gets called multiple times.
I'm clearly missing a trick. I can understand the digest cycle and I do have expressions in the page that need to be checked so I can see why the controller is running multiple times, but I cannot understand how I can get it to exclude the web calls after they've run once.
Upvotes: 2
Views: 1250
Reputation: 842
Being called $http
service twice or more may be due to many reasons. Few I am listing below:
ng-controller='HomePanel'
in html) name in template.If you are using ngRoute
, and mentioning controller name in template, as well in route config, it may be calling twice. For example. In app.js
app.config([ '$routeProvider', '$sceProvider',
function($routeProvider, $sceProvider) {
$routeProvider.when('/', {
templateUrl : 'Home',
controller : 'HomePanel',
});
}]);
and in HTML:
<script type="text/ng-template" id="Home">
<div ng-controller="HomePanel">
</div>
</script>
Don't let you ajax call to cache. So append some random value in end of your URL.
var req =
{
method: 'GET',
url : someUrl + "&random="+ Math.random();
};
Hope this may help.
Upvotes: 2
Reputation: 98
Instead of using $http in controller put it in a function in a custom service and call that function when you want to update data from controller or you can call $http in service and assign it to a variable and use that in controller.
Upvotes: 0