bigpotato
bigpotato

Reputation: 27517

Angular beginner: How to use factories + $http + json file?

I have a factory that doesn't work:

toDoListApp.factory("blahFactory", function($http) {
    return {
        getChores : function() {
            return $http({
                url: '/chore.json',
                method: 'GET'
            })
        }
    }
});

And a chore.json file that has data:

{"name":"laundry","hours":"3"},{"name":"dishes","hours":"0.5"},{"name":"blah","hours":"1.5"}

And my controller uses this factory but breaks on that line:

toDoListApp.controller("ChoresController", function($scope, choresFactory, blahFactory) {

    blahFactory.getChores().success(function(data) {
        $scope.blah = data;
        console.log(data);
    });

    ....

The trace in my firebug console is not very descriptive: Error: JSON.parse: unexpected non-whitespace character after JSON data + a bunch of angular junk that does not make sense. Can anyone help explain? Is my JSON invalid?

=== UPDATE ===

Ok so I'm trying to put the array brackets into the json file and modified the $http.get function in my factory to use cache: false but it still doesn't update my json because it's cached...

=== ANSWER ===

So I deleted chrome's cache and added array brackets and everything worked!

Upvotes: 0

Views: 136

Answers (1)

Tyler McGinnis
Tyler McGinnis

Reputation: 35276

Your JSON isn't correct. You just have three objects next to each other, instead, put those in an array like this.

[
  {"name":"laundry","hours":"3"},
  {"name":"dishes","hours":"0.5"},
  {"name":"blah","hours":"1.5"}
]

everything else looks great.

Upvotes: 3

Related Questions