Sri Chatala
Sri Chatala

Reputation: 177

how to call angularJS service into a controller that is not included in a controller?

how to call angularJS service into a controller that is not included in a controller?

productCtrl.js

 var app = angular.module('myApp',[]);

app.controller('productCtrl',['$scope','productService', function ($scope,campaignService) 
  {
      $scope.getLocations = function() {
      productService.getPorduct(response,status);
  }
}]);

productService.js

var app = angular.module("myApp", []);

app.service('productService', ['ajaxService', function (ajaxService) {

this.getPorduct = function (successFunction, errorFunction) {

   ajaxService.AjaxGet("http:location.com/product#?clientid=10",    

successFunction, errorFunction);

  };
}]);

ajaxService.js

var app = angular.module("myApp", []);

app.service('ajaxService', ['$http', 'blockUI', function ($http, blockUI) {

this.AjaxGet = function (route, successFunction, errorFunction) {
    blockUI.start();
    setTimeout(function () {
        $http({ method: 'GET', url: route }).success(function (response, status, headers, config) {
            blockUI.stop();
            successFunction(response, status);
        }).error(function (response) {
            blockUI.stop();
            errorFunction(response);
        });
    }, 1000);

}

}]);

When I access the controller to get the result from url, I am getting following error angular.js:13294 Error: [ng:areq] Argument 'productCtrl' is not a function, got undefined

Upvotes: 2

Views: 955

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Make sure you should define angular module with same name should only created once per application & then utilize that module for extending component to it.

Here I can see three places where you have created module like

var app = angular.module("myApp", []);

It should be created only once and then used like angular.module("myApp") where you wanted to add component to this module

productService.js & ajaxService.js should use module initially created module by productCtrl.js(assuming productCtrl.js loaded first). You need to change productService.js & ajaxService.js code from

var app = angular.module("myApp", []);

to

var app = angular.module("myApp");

Even better remove var app = angular.module("myApp", []); this line from other js file which are loaded later, then they will use app variable which is already loaded with myApp module

Upvotes: 0

Igor
Igor

Reputation: 62213

Only call the module with [] once, after that just use the module name.

// Creates the module
var app = angular.module("myApp", []);

// call the same module from your other files
var app = angular.module("myApp"); // no []

See the documentation here.

In a nut shell with [] creates a new instance while without [] retrieves an existing/already created instance. Be sure your scripts are ordered so the first call is always with the [] parameter.

Upvotes: 1

Related Questions