vineet
vineet

Reputation: 14236

Prevent auto calling function in angularjs service

I am new to AngularJs and i have an issue that when i run my app, the factory function call twice time. I want to prevent by calling function from Factory function.

Here is my code:-

advisoryApp.config(function ($routeProvider) {
    $routeProvider
            .when('/', {
                templateUrl: 'pages/home.html',
                controller: 'mainCtrl'
            })
            .when('/about', {
                templateUrl: 'pages/about.html',
                controller: 'aboutController'
            })
            .when('/contact', {
                templateUrl: 'pages/contact.html',
                controller: 'contactController'
            });
});

advisoryApp.factory('HttpResponse', function ($http) {
    return{
        getHttpResponse: function (method, url, data) {
            return $http({
                url: url,
                method: method,
                data: data
            })
        }
});

advisoryApp.controller('mainCtrl', function ($scope, HttpResponse, $rootScope) {
    $scope.allAdvisoryData = '';
    var segment_id = 5;
    var url = $rootScope.base_url + "web_service/call_listing/" + segment_id;
    var data = 'segment_id=' + segment_id;

    $scope.message = 'Everyone come and see how good I look!';
    HttpResponse.getHttpResponse('POST', url, data).success(function (data) {
        console.log(data);
    });
});

Here is my output:-

Here api i.e POST http://localhost/advisory_mandi/web_service/call_listing/5 call twice but i want, it should call only one time. enter image description here

Upvotes: 0

Views: 609

Answers (1)

Ruben Nagoga
Ruben Nagoga

Reputation: 2218

Most common reason is that you initialise your controller twice. Few options:

  • Controller initialised from router and from html with ng-controller
  • Application initialised twice. Maybe you call ng-app twice
  • Application bootstrapped from javascript and also from html

Upvotes: 2

Related Questions