Matoy Matoy - 5 months ago 51
AngularJS Question

cannot access angular service from external js file

this is my html:

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

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


and this is my services.js file:

var app=angular.module("myApp", []);
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}main.html
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

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) {