Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am decently new to AngularJS, so apologies in advance is this is a basic solve. I want to be able to access and add to an external .json file using AngularJS. When I hard-code the data within a factory, it shows up fine. However, when I try to access the data using Angular's $http, nothing shows up.

Here is my factory:

sampleApp.factory('findSamplesFactory', function($http) {
    var samples = $http.get('sample.json').success(function(response) {
        return response;
    });

    var factory = {};
    factory.getSamples = function() {
        return samples;
    };
    factory.insertSamples = function(sampleNumber, sampleBox, sampleRow, sampleLevel) {
        samples.push({
            number: sampleNumber,
            box: sampleBox,
            row: sampleRow,
            level: sampleLevel
        });
    };

    return factory;
});

And here is the controller I have set up

sampleApp.controller('sampleAppController', function ($scope, findSamplesFactory) {
    $scope.samples = findSamplesFactory.getSamples();

    $scope.addSamples = function() {
        var sampleNumber = $scope.newSample.number;
        var sampleBox = $scope.newSample.box;
        var sampleRow = $scope.newSample.row;
        var sampleLevel = $scope.newSample.level
        findSamplesFactory.insertSamples(sampleNumber, sampleBox, sampleRow, sampleLevel);
        $scope.newSample.number = ' ';
        $scope.newSample.box = ' ';
        $scope.newSample.row = ' ';
        $scope.newSample.level = ' ';
    };
});

The .json file validates fine. Any help would be appreciated!

EDIT: Here is a Plunker of my full app: http://plnkr.co/edit/2itJiB?p=preview

share|improve this question

1 Answer 1

I changed the following and it worked. Note the change $scope.samples = data.data;

sampleApp.controller('sampleAppController', function ($scope, findSamplesFactory) {

    findSamplesFactory.getSamples().then(function(data){
      $scope.samples = data.data;  // I changed this.
    });
  ...Your code as it is...
  });

Check the [plunker]: http://plnkr.co/edit/sZTme6?p=preview

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.