11

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

enter image description here

iamdash
  • 449
  • 1
  • 3
  • 15
  • The answer at the bottom with the highest upvotes (currently 33) should be marked as the correct answer for this question. – HelpMatters Mar 14 '16 at 12:53

3 Answers3

53

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.

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
Jeremy D
  • 955
  • 10
  • 8
5

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

Network console only one HTTP call

Edit:

Updated plunk with a dummy json file

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

Same seen in logs

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.

Abhishek Nandi
  • 4,265
  • 1
  • 30
  • 43
  • Thanks for that. Yes, I see that now; status outputs 1. However, Dev tools console is showing two "XHR finished loading" messages to the same URL? Is this a feature of dev tools? – iamdash Jul 31 '13 at 10:32
  • in the console 1 get to see only one log for XHR finished loading for the url /json-tags-test. I will attached the screenshot as well. also please accept the answer if it helps you. Thanks – Abhishek Nandi Jul 31 '13 at 10:39
  • OK, I see that, but it is attempting to load it twice in the Plunk too. Unless I am missing something. I have attached a screenshot to my OP so you can see, the difference being that it finds /jason-tags-test in the first call obviously. – iamdash Jul 31 '13 at 12:30
  • @Dashman I checked it once again, its getting called only once and not twice. have attached the logs, screenshots and an updated plunk with a dummy file.. – Abhishek Nandi Jul 31 '13 at 12:48
  • 1
    Wow, ok I have been completely overlooking the fact I had Angular concatenated in my lib-min file, and then another ref to it. This was causing it to run twice. Marking you answer as accepted as confirmed the code itself was OK. – iamdash Jul 31 '13 at 12:59
0

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'
                   },
               }
           });
SFK
  • 1
  • 2