Reputation: 11
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
Upvotes: 1
Views: 2276
Reputation: 1599
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
Upvotes: 1