AngularJS calls HTTP multiple times in controller

I am developing a page with Angular, and have an init() method in my controller. The code is as follows:

var filtersController = ['$scope', '$http', function ($scope, $http) {
    $scope.init = function () {
        $http({
            method: 'GET',
            url: '/json-tags-test',
            cache: true
        }).success(function (data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
        }).error(function (data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
   };
}];

It is just a call to a simple JSON file.

My HTML is as follows:

<div class="container main-frame" ng-app="projectsApp" ng-controller="filtersController" ng-init="init()">
</div>

For some reason, this get call gets call twice every time I load the page. Is this standard behaviour?

Many thanks,

Dash

Answers


This problem may also be caused by having an ng-app with routing to your controller and an ng-controller reference in your page. For example, if your app looks like:

<html lang="en" ng-app="myApp">
<head>...</head>
<body>
<div ng-controller="myController">
...
</div>
</body>
</html>

Javascript defining the app:

angular.module('myApp',[]) {
$routeProvider.when('/path', {templateUrl: '...', controller: myController);

In the case above, with the defined routing to myController, the controller will be instantiated twice and you'll see two calls as described.

Updated

Above code describe what is problem but what is proper solution is missing so I updated answer as per @Intrepid comment.

Need to remove ng-controller="myController" from your html template if you already defined in route.


I don't think it is getting called twice, i just created a plunk for you to see this.

var app = angular.module('projectsApp', []);
app.controller('filtersController', ['$scope', '$http', function ($scope, $http) {
  $scope.status = 'Page loading';
  var count = 0;
    $scope.init = function () {
      $scope.status = 'API called';
        $http({
            method: 'GET',
            url: '/json-tags-test',
            cache: true
        }).success(function (data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
            console.log('success');
            count++;
            $scope.status = 'successful: '+ count;
        }).error(function (data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.log('error');
            count++;
            $scope.status = 'failed times: '+ count;
        });
   };
}]);

XHR logs from DEV tools

Edit:

Updated plunk with a dummy json file

http://plnkr.co/edit/hTdtLK?p=preview

As you can see once again that its getting called only once. Clear the logs i guess you are seeing the logs for the previous page load, coz changes are immediately visible when in preview mode.


If you are using UI-Router, better to use controllerAs in config and remove ng-controller in the view.

 .state('master.userlist', {
               url: "userlist",
               views: {
                   userlist: {
                       templateUrl: 'app/user/userlist.html', 
                       controller: 'UserController',
                       controllerAs:'vm'
                   },
                   'detail@master.userlist': {
                       templateUrl: 'app/user/userdetail.html'
                   },
               }
           });

Need Your Help

Java 8 streams conditional processing

java java-8 java-stream

I'm interested in separating a stream into two or more substreams, and processing the elements in different ways. For example, a (large) text file might contain lines of type A and lines of type B,...

Find out if MPMoviePlayerController is currently playing

iphone ios objective-c mpmovieplayercontroller

I have one small problem regarding MPMoviePlayerController, i have a link that play movie when i click on that movie button, however when i click on another button the application gets crashed, i ...