【问题标题】:How to iterate over an array stored in an object using ng-repeat如何使用 ng-repeat 迭代存储在对象中的数组
【发布时间】:2017-03-13 23:27:25
【问题描述】:

我调用了一个返回单个对象的 API 端点。我想遍历存储在对象中的名为video 的数组,并将存储在数组中的所有链接返回到视图。

从 API 返回的 JSON 对象

html代码

<div class="myVideo" ng-repeat="v in courses.video">
     <iframe width="560" height="315" ng-src="{{'v.video'}}" 
      frameborder="10" allowfullscreen></iframe>
</div>

用于 API 调用的控制器中的功能

$scope.getCourse = function(id){
        coursesFac.getCourseById(id)
            .then(function (response) {
                $scope.courses = response.data;
                var items =response.data;
                console.log(items);
                //console.log($scope.courses.video);
            }, function (error) {
                $scope.status = 'Unable to load course data: ' + error.message;
                console.log($scope.status);
            });
    };

此错误出现在应显示视频的视图中

【问题讨论】:

  • 看起来courses.video 中的数组是一个字符串,请先尝试将其转换为数组,因为我没有发现您的 ng-repeat 有任何问题

标签: javascript angularjs arrays angularjs-ng-repeat


【解决方案1】:

courses.video 是一个字符串 - 不是一个数组。你需要解析json

$scope.getCourse = function(id) {
    coursesFac.getCourseById(id)
        .then(function(response) {
            response.data.video = JSON.parse(response.data.video); //HERE
            $scope.courses = response.data;
            var items = response.data;
            console.log(items);
            //console.log($scope.courses.video);
        }, function(error) {
            $scope.status = 'Unable to load course data: ' + error.message;
            console.log($scope.status);
        });
};

【讨论】:

  • 这也适用于enroled(没有错字)
  • @Weedoze 所以我将数组的解析添加到 json 中,如您在答案中所示。但我仍然收到localhost:8080/v.video404 () 错误。我在这里想念什么。谢谢
  • @SeanMcGrath 你想用这个网址做什么? 404 表示未找到...这与提供的代码无关
  • 我已编辑问题以显示视图中显示的错误消息。我想要的是所有视频链接都显示在视图中。当我在数组上重复时,我希望显示视频。
  • @SeanMcGrath 我回答了这个问题。 JSON 解析出错。此错误已解决。现在你又遇到了另一个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多