1

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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.