javascript - AngularJS - 如何访问对象中的数组以在 ng-bind 中使用

标签 javascript angularjs arrays object angularjs-ng-repeat

我正在学习 AngularJS,我正在尝试将“经过清理”的标题插入到 ng-repeat 中的 h2 中,但是我无法弄清楚如何访问对象中数组中的数据。其他一切正常,我只需要“title”值。

HTML:

<div ng-repeat="question in questions" ng-show="!!questions.length" class="question-list">              
<h2><a ng-href="{{question.link}}" title="{{question.title}}" target="_blank" ng-bind-html="title"></a></h2>
</div>

这是 JS:

var loadFeed = angular.module('loadFeed', ['ngSanitize']);

loadFeed.controller('feedController', ['$scope', '$http', function($scope, $http) {

    $scope.questions = [];    
    $http({
        method: 'GET',
        url: 'https://api.stackexchange.com/2.2/questions?pagesize=10&order=desc&sort=votes&tagged=angular&site=stackoverflow'
    }).then(function(feed) {

        console.log('success');
        console.log(feed);

        $scope.questions = feed.data.items;
        console.log($scope.questions);  

        $scope.title = $scope.questions.title; // This is what I need for the ng-bind


    },function(error) {
        console.log('error');
        console.log(error);
    }); 

}]);

这会返回一个单独的值(第一个项目的标题):

$scope.title = $scope.questions[0].title;

但是,我需要这个结果(它是空白的):

$scope.title = $scope.questions.title;

我已经尝试了 angular.forEach 和 JS 循环,但这只是重复了一个列表项中的每个标题。

有什么我遗漏的吗?

最佳答案

如果您希望每个链接显示其对应问题的标题,则将 ng-bind-html="title" 更改为 ng-bind-html="question.title"。您正处于 ng-repeat 的中间,并且在该上下文中 question 是当前呈现的任何问题对象,因此 question.title 是该问题的标题.

我认为上面的内容应该可以解决您的问题,但是如果您想获取问题数组并生成一个仅包含标题的新数组,您可以使用 Array.map:

var titles = $scope.questions.map(function (question) {
    return question.title;
});

这将遍历数组,从每个数组中取出标题,并生成一个仅包含标题的新数组。

关于javascript - AngularJS - 如何访问对象中的数组以在 ng-bind 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46647662/

相关文章:

javascript - 具有用户交互性的 3D 绘图

javascript - 根据选择显示隐藏输入元素

javascript - Array.prototype.find() 意外行为

javascript - 使用 mysql 和流传感器数据绘制 d3 实时图形

angularjs - href ="#"导致位置地址改变,我们可以避免吗?

javascript - 列表上的自动换行

javascript - 在链接内使用监视会导致无限的摘要循环。

java 提示数组的数组的数组索引越界

c++ - 将数组的值成对求和,直到最终得到所有值的总和

将二维数组转换为动态数组会导致核心转储