Reputation: 567
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', []);
Upvotes: 1
Views: 644
Reputation: 567
I fixed the problem, in fact and for security reasons, AngularJS can't read local json files . It only reads online ones. Thanks for those who helped me ^^
Upvotes: 0
Reputation: 3746
There seems to be 2 issues with your code
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>
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.
Upvotes: 2
Reputation: 1895
in the html you defined
<body ng-app="app">
But in the js you are using:
var app = angular.module('FolderApp', []);
Change one of the 2 and place
<script src="js/app.js"></script>
on top and you should be ok
Upvotes: 1
Reputation: 512
Try loading <script src="js/app.js"></script>
before the other files (but after the angular core)
Upvotes: 1
Reputation: 23642
The order of the files matter... place your app.js
at the top and also your app-name
defined in your html should match the js
too.
Upvotes: 1