如何使用工厂和AngularJS中的$ http访问JSON文件中的数据?

时间:2013-06-06 19:37:02

标签: json http angularjs get factory

我是AngularJS的新手,所以提前道歉这是一个基本的解决方案。我希望能够使用AngularJS访问并添加到外部.json文件。当我在工厂内硬编码数据时,它显示正常。但是,当我尝试使用Angular的$ http访问数据时,没有任何显示。

这是我的工厂:

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;
});

这是我设置的控制器

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 = ' ';
    };
});

.json文件验证正常。任何帮助将不胜感激!

编辑:这是我的完整应用程序的Plunker:http://plnkr.co/edit/2itJiB?p=preview

1 个答案:

答案 0 :(得分:1)

我更改了以下内容并且有效。 请注意更改$ 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...
  });

检查[plunker]:http://plnkr.co/edit/sZTme6?p=preview