Matoy Matoy - 1 year ago 124
AngularJS Question

cannot access angular service from external js file

this is my html:

<link rel="stylesheet" type="text/css" href="css/style.css">
<script src=""></script>

<script type="text/javascript" src="services.js"></script>
<div ng-app="myApp" ng-controller="myCtrl2">
hello {{x}}
var app=angular.module("myApp", []);
app.controller("myCtrl2", ['$scope','$location', function($scope, $location) {

and this is my services.js file:

var app=angular.module("myApp", []);
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
function get() {
return savedData;

return {
set: set,
get: get


why doesn't I get hello world but instead chrome developers tool say: ReferenceError: myService is not defined

Answer Source

You need to correct couple of things

  1. Don't recreate a myApp module on html page, that will destroy old registered component of module. Instead use the existing myApp module created by services.js.

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

    should be

    var app=angular.module("myApp");
  2. Do inject service before using it in controller.

    app.controller("myCtrl2", ['$scope','$location', 'myService', 
        function($scope, $location, myService) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download