IAmAkittycatAMA IAmAkittycatAMA - 5 months ago 22
AngularJS Question

Factory Service unable to load json file

I have a

JSON
file,
data.json
, in the same folder as the file below. When I run this however it's returning not found.

I have also tried putting the
$http.get
request in a factory, but same result - not found. I also tried changing the
.json
extension to
.txt
as was suggested elsewhere, but this also didn't work.

The rest of the code came with the angular seeds project.

Is there something i'm missing in the other files or some other trick to the get request?

'use strict';

var myApp = angular.module('myApp.view1', ['ngRoute']);

myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}]);

myApp.controller('View1Ctrl', [

'$scope',
'$http',

function($scope, $http) {
$http.get('data.json')
.then(function(res){
$scope.quiz = res.data
});
}]);

Answer

The .json file must not be in the same folder as the js file. Relative paths are resolved relative to the including index.html file. If you have this structure:

+-index.html
|-folder
| \-data.json
\-js
  \-app.js

You have to $http.get("folder/data.json") in app.js to make it work.