如何在Angular控制器中链接外部json文件?

时间:2017-02-09 11:00:24

标签: javascript angularjs json

我正在尝试制作我的第一个Angular JS项目,现在我需要将json数组从我的控制器导出到外部json文件,这是我的控制器和json:

Fantacalcio.controller('fantacalcioController', function($scope){
  $scope.miaSquadra = [
      {
        Giocatore: {
          nome: "Orestis",
          cognome:"Karnezis"
        },
          mediaVoto: "4.91",
          squadra: "Udinese"
        },

    .....
        Giocatore: {
          nome: "Patrick",
          cognome:"Schick"
        },
          mediaVoto: "6.97",
          ruolo: "attaccante",
          squadra:"Sampdoria"
      }
];

});

这是我的组成部分:

Fantacalcio.component('tabella', {
    templateUrl: 'components/tabella.html',
    controller: 'fantacalcioController'
  });

我怎么能把json数组放在外部json文件中? 我知道我应该使用$ http来获取请求,但我不知道如何使用它,我尝试了这个解决方案https://docs.angularjs.org/tutorial/step_07,但我无法使其工作。

谢谢。

1 个答案:

答案 0 :(得分:0)

写得像:

url : '/1',
templateUrl : 'partials/1.html',
controller : function($scope, $http, $log){
  $http.get('phones/phones.json').then(function(response) {
      $scope.phones = response.data.phones;
  });
}

在组件中使用$ scope而不是self this或在控制器“fantacalcioController”中编写以下代码

  $http.get('phones/phones.json').then(function(response) {
      $log.log(response.data.phones);
      $scope.phones = response.data.phones;
  });

其中phones文件夹位于您的应用根文件夹中。和phones.json里面的手机文件夹。

相关问题