Tushar Balar
Tushar Balar

Reputation: 751

Service injection into controller having in seperate files with AngularJS

When i try to inject service into controller which I have in separate file mentioned in below code i get error:

TypeError: myService.getData is not a function at new (controllers.js:18) at Object.e [as invoke] (angular.min.js:39) at M.instance (angular.min.js:80) at D (angular.min.js:61) at g (angular.min.js:55) at g (angular.min.js:55) at angular.min.js:54 at angular.min.js:20 at r.$eval (angular.min.js:133) at r.$apply (angular.min.js:134)

index.html

load all js files in this html page

<!DOCTYPE html>
<html lang="en" ng-app="app">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>title</title>
  <link rel="stylesheet" href="styles/all.css">
  <script src="libs/angular.min.js"></script>
  <script src="libs/jquery.js"></script>
  <script src="js/service.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/myApp.js"></script>
  <script src="libs/bootstrap/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
</body>
</html>

This is the main file where we load controllers and services at once

myApp.js

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

service.js

here i tried to get data from server and wants to use in controller

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

app.service('myService', function($http) {
  function getData (callbackFunc) {
    $http({
        method: 'GET',
        url: "url"
      }).success(function(data){
        callbackFunc(data);
    }).error(function(){
        alert("error");
    });
  }
});

controllers.js

This file include all logic and inject myService from service.js file. i use myService from service.js and tried to get data, but i got an error all the time

angular.module('app.controllers', ['app.service'])

  .controller('myCtrl', ['$scope', '$http', '$timeout', 'myService',

    function ($scope, $http, $timeout, myService) {

   myService.getData(function(dataResponse) {

          $scope.surveys = dataResponse;

});

}]);

Upvotes: 1

Views: 669

Answers (1)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Your service module declaration has problem.

You are getting module name without declaring it.

Try like this

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

appSvc.service('myService', function($http){}); 

bind Your method with this

Like this

this.getData =function (callbackFunc) {}

Upvotes: 1

Related Questions