nour nour - 7 months ago 14
Javascript Question

Uncaught Error: [$injector:modulerr] & Uncaught ReferenceError: app is not defined

I am using AngularJS 1.3.5 and I am trying to get an information from a json file.
Here is my code:
The HTML file:



<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="js/controllers/MainController.js"></script>
<script src="js/services/myapp.js"></script>
<script src="js/app.js"></script>
<body ng-app="app">

<div ng-controller="MainController">


<div ng-repeat="content in contents">


<a ng-href="{{data.FolderPath}}">{{data.FolderPath}}</a>



</div>


</div>
</body>
</html>





Javascript files:
MainController.js



app.controller('MainController', ['$scope', 'myapp', function($scope, myapp) {
myapp.success(function(data) {
$scope.FolderPath = data;
});
}]);





myapp.js



app.factory('myapp', ['$http', function($http) {
return $http.get('C:\Users\nouri\Desktop\configFile.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);





and finally app.js



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




I corrected the errors hwoever now I am having a white screen so my code didn't read what is in my json file:
{
"FolderPath": "C:\Users\nouri\Desktop\test"
}
what should I doenter image description here

Answer

There seems to be 2 issues with your code

  1. Order in which you are loading the scripts. Load app.js followed by services/myapp.js and then controllers/MainController.js.

        <script src="js/app.js"></script>
        <script src="js/services/myapp.js"></script>
        <script src="js/controllers/MainController.js"></script>

  2. The name of your angular module is FolderApp but you have referenced it as 'app'. Change it as

        <body ng-app="FolderApp">

EDIT
There is an issue with the way you are using your factory. You should return an object containing a method that will call the API and return back the $http promise. Try something like this:

Factory

app.factory('myapp', ['$http', function($http) { 
   return {
    getJson: function() {
       return $http.get('C:\Users\nouri\Desktop\configFile.json');
    }
  }
}]);

Controller

app.controller('MainController', ['$scope', 'myapp', function($scope, factory) {
  factory.callApi()
    .then(function(data) {
      $scope.FolderPath = data;
    });
}]);

Take a look at this fiddler.