代码之家  ›  专栏  ›  技术社区  ›  Laura

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

  •  1
  • Laura  · 技术社区  · 7 年前

    我正在学习AngularJS,我试图在一个 h2 ng-repeat 但是,我无法确定如何访问对象中数组内的数据。其他一切都很好,我只需要' 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循环只是重复一个列表项中的每个标题。

    我有什么遗漏吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Nicholas Tower    7 年前

    如果希望每个链接显示其相应问题的标题,请更改 ng-bind-html="title" ng-bind-html="question.title" question 是当前正在渲染的问题对象,因此 question.title 是那个问题的标题。

    我认为上面的方法应该可以解决您的问题,但是如果您想获取问题数组并生成一个只包含标题的新数组,您可以使用数组。地图:

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

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