【问题标题】:How to load json file into Angularjs for ng-repeat如何将 json 文件加载到 Angularjs 中以进行 ng-repeat
【发布时间】:2014-12-01 03:46:09
【问题描述】:

我有一个简单的 json 文件,其中包含艺术家姓名列表,例如

["Vincent van Gogh", "Leonardo da Vinci", "Pablo Picasso"]

我不知道如何将此外部 json 文件加载到 angularjs 数组中并在其上使用 ng-repeat。我试过的非工作代码是:

<tr ng-repeat="artist in artists">
    <td>{({ artist })}</td>
    <td></td>
</tr>

<script>
var artApp = angular.module('artApp', []);

artApp.config(function($interpolateProvider){
    $interpolateProvider.startSymbol('{({').endSymbol('})}');
});

artApp.controller('mycontroller', function($scope,$http){
   $scope.artists = [];
   $http.get('/home/user/artist_names.json').success(function(data) {
      angular.forEach(data.MainRegister,function(entry) {
         $http.get(entry.url).
          success(function(data) {
            $scope.artists.push(angular.extend(entry,data.SubInformation);
         });
      });
   });
});
</script>

这个控制器代码不仅不起作用,而且它破坏了我的$interpolateProvider 代码并使 html 实际显示我的原始角度变量。

【问题讨论】:

    标签: javascript json angularjs


    【解决方案1】:

    ng-repeat 底部的示例链接

    artApp.controller('TodoCtrl', function($scope, $http) {
    $http.get('/home/user/artist_names.json')
           .then(function(result){
              $scope.artists = result.data;                
            });
    });
    

    在 html 中

      <ul>
        <li ng-repeat="artist in artists">
          {{artist.name}}
        </li>
      </ul>
    

    在您的 JSON 中

    [{ "name":"Vincent van Gogh"},
     { "name":"Leonardo da Vinci"},
     { "name":"Pablo Picasso"}]
    

    http://plnkr.co/edit/Wuc6M7?p=preview

    来自 jaime

    我在 Azure 中托管的节点服务器遇到了这个问题,并且修复了 是为了确保 JSON 文件的 mime 类型设置正确。我曾是 在 azure 中托管,这意味着确保 web.config 与 正确的设置,但我不确定 Django 需要什么。没有 服务器将报告您提到的 404 的正确 mime 类型。

    来自山姆故事

    【讨论】:

    • 我的 django 开发服务器尝试获取我的 json 文件时出现 404 错误。
    • 把它放在我的 django static 文件夹中,因为我的应用知道那个文件夹。
    • 很高兴听到你得到它!
    【解决方案2】:

    我在 Azure 中托管的节点服务器上遇到了这个问题,解决方法是确保正确设置 JSON 文件的 mime 类型。我在 azure 中托管,这意味着确保 web.config 存在正确的设置,但我不确定 Django 需要什么。如果没有正确的 mime 类型,服务器会像您提到的那样报告 404。

    【讨论】:

    • 我通过将 json 文件放入我的 django settings.py 文件中引用的 static 文件夹来修复它。您提到web.config 让我想到将 json 文件放入 django 知道的文件夹中。
    • 很高兴听到你想通了!
    【解决方案3】:

    你可以试试这个:

     $http.get("/home/user/artist_names.json")
        .success(function(response) {$scope.artists = response;});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多