Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular factory always called twice

Tags:

angularjs

I am calling a REST service from angular and it always calls the factory twice. Here is the factory code.

app.factory('dataFactory', ['$http', function ($http) {
    var urlBase = '/api';
    var dataFactory = {};

    dataFactory.getMyItems = function () {            
        return $http.get(urlBase + '/MyItems');
    };

    return dataFactory;
} ]);

It's called from the controller here

app.controller('MyItemsController', ['$scope', 'dataFactory',
    function ($scope, dataFactory) {            
        $scope.myItems;

        getItems();

        function getItems() {

            dataFactory.getMyItems()
                .success(function (itemsData) {
                    $scope.myItems = itemsData;
                })
                .error(function (error) {
                    $scope.status = 'Unable to load items data: ' + error.message;
                });
        }
    }
]);
like image 688
Heinrich Avatar asked Mar 27 '14 02:03

Heinrich


1 Answers

I had the same problem as yours where the controller in general was called twice; hence, the factory will be called twice.

But after looking at this solution: Combating AngularJS executing controller twice

Step 1:

Make sure you are adding the service and controller in your (main layout view) only once.

Example:

index.html

  <script src="../MyItemsController.js"></script>
  <script src="../MyItemsService.js"></script>

If the problem still persists after doing step 1 go to step 2


Step 2:

There are two ways to do it:-

1. Either keep the controller in your view (ng-controller), and remove it from your config route like this:

route config (usually, app.js):

 app.config(['$routeProvider', function($routeProvider){
      $routeProvider.when('/',
               { 
                   templateUrl: 'pages/home.html'
                   //Remove controller from here
               });
}]);

home.html

 <!-- Add the ng-controller in your view -->
    <div ng-controller="MyItemsController">
        <!-- Your stuff -->
    </div>

2. Or keep the controller in your config route, and remove ng-controller from view like this:

route config (usually, app.js):

  app.config(['$routeProvider', function($routeProvider){
      $routeProvider.when('/',
               { 
                   templateUrl: 'pages/home.html',
                   controller: 'MyItemsController' //Add the controller here

               });
}]);

home.html

 <!-- Remove the ng-controller in your view -->
    <div>
        <!-- Your stuff -->
    </div>

Note: The above solution works with ui router as well.

like image 194
Abzoozy Avatar answered Sep 21 '22 14:09

Abzoozy