javascript - 如何将 json 文件加载到 Angularjs 中以进行 ng-repeat

标签 javascript json angularjs

我有一个简单的 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>

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

最佳答案

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

I ran into this issue with a node server hosted in Azure and the fix was to ensure the mime type for JSON files was set properly. I was hosting in azure so that meant ensuring a web.config existed with the right settings, but I'm not sure what's required with Django. Without the proper mime type the server would report a 404 like you mentioned.

来自山姆故事

关于javascript - 如何将 json 文件加载到 Angularjs 中以进行 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27221399/

相关文章:

javascript - 如何使用 JavaScript 更新保存在 JSON 文件中的数据?

javascript - 在 Angular JS 中处理模式最简单的方法是什么?

ios - JSON转UITableView Swift 4 最近播放的歌曲

angularjs - 空对象需要 Angular 浏览器

javascript - 部署缩小的 JavaScript 文件并进行调试

javascript - jQuery.ajax 和 Rickshaw - 回调函数?

javascript - 异步函数 promise 何时解决?

javascript - Angular 5 删除查询参数

javascript - 为什么我不能在 Node v0.11.11 中使用 Promise?

json - 如何分析 Web 服务?