1

我对 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

4

1 回答 1

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

于 2014-09-10T19:54:05.000 回答