【问题标题】:Can't render JSON results in ng-repeat无法在 ng-repeat 中呈现 JSON 结果
【发布时间】:2017-05-19 23:07:22
【问题描述】:

我正在尝试遍历从搜索 Spotify REST API 返回的嵌套 JSON 对象,但无法呈现结果。

在我的控制器中:

function fetch() {
  $http.get("https://api.spotify.com/v1/search?q=" + $scope.search + "&type=artist&limit=50")
    .then(function(response) {
      console.log(response.data.artists.items);
      $scope.details = response.data.artists.items;
    });
}

它返回一个看起来像这样的对象:

我正在尝试通过以下方式循环响应:

<div ng-if="details.response==='True'">
  <ul ng-repeat="song in details">
    <li>Songs:{{song.name}}</li>
  </ul>
</div>

并显示external_urls 值、images url 以及name 值。然而,这些都没有被渲染(甚至没有Songs这个词,无论我是否有正确的值都应该显示)。

【问题讨论】:

  • 您的问题出在 ng-if 子句中,您的评估是一个没有表现的布尔值,您需要声明一个布尔值,当响应包含数据时该值变为真。这也是您看不到 Songs 一词的原因,div 根本没有显示,因为它正在被评估为无法解释的值
  • ...具体来说,您的details 不包含response,它包含items 的数组。

标签: angularjs json angularjs-ng-repeat


【解决方案1】:

更改ng-if 子句

让它评估为实际的boolean,当响应有数据时变为真。

类似:

.then(function(response) {
      console.log(response.data.artists.items);
      $scope.isTheDataLoaded = true;
      $scope.details = response.data.artists.items;

在你的 html 中:

<div ng-show="isTheDataLoaded">

【讨论】:

    【解决方案2】:

    将 if 条件更改为

    <div ng-if="details">
        <ul ng-repeat="song in details">
            <li>Songs:{{song.name}}</li>
        </ul>
    </div>
    

    因为“详细信息”不包含“回复”。所以你只需要检查它是否存在或者它是否不为空

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      相关资源
      最近更新 更多