AngularJS - 如何访问 object 中的数组以在 ng-bind 中使用
AngularJS - how to access array in object to use in ng-bind
我正在学习 AngularJS,我正在尝试将 'sanitised' 标题插入到 ng-repeat
中的 h2
,但是我不知道如何访问 object 中数组内的数据。其他一切正常,我只需要“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=Whosebug'
}).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);
});
}]);
这 return 一个单独的值(第一项的标题):
$scope.title = $scope.questions[0].title;
但是,我需要这个结果(它是空白的):
$scope.title = $scope.questions.title;
我试过 angular.forEach
和 JS 循环,但是这只会重复一个列表项中的每个标题。
有什么我遗漏的吗?
如果您希望每个 link 显示其对应问题的标题,请将 ng-bind-html="title"
更改为 ng-bind-html="question.title"
。您正处于 ng-repeat 的中间,在这种情况下 question
是当前正在呈现的问题 object,因此 question.title
是该问题的标题。
我认为上面的内容应该可以解决您的问题,但是如果您想获取问题数组并生成一个仅包含标题的新数组,您可以使用 Array.map:
var titles = $scope.questions.map(function (question) {
return question.title;
});
这将遍历数组,从每个数组中提取标题,并生成一个仅包含标题的新数组。
我正在学习 AngularJS,我正在尝试将 'sanitised' 标题插入到 ng-repeat
中的 h2
,但是我不知道如何访问 object 中数组内的数据。其他一切正常,我只需要“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=Whosebug'
}).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);
});
}]);
这 return 一个单独的值(第一项的标题):
$scope.title = $scope.questions[0].title;
但是,我需要这个结果(它是空白的):
$scope.title = $scope.questions.title;
我试过 angular.forEach
和 JS 循环,但是这只会重复一个列表项中的每个标题。
有什么我遗漏的吗?
如果您希望每个 link 显示其对应问题的标题,请将 ng-bind-html="title"
更改为 ng-bind-html="question.title"
。您正处于 ng-repeat 的中间,在这种情况下 question
是当前正在呈现的问题 object,因此 question.title
是该问题的标题。
我认为上面的内容应该可以解决您的问题,但是如果您想获取问题数组并生成一个仅包含标题的新数组,您可以使用 Array.map:
var titles = $scope.questions.map(function (question) {
return question.title;
});
这将遍历数组,从每个数组中提取标题,并生成一个仅包含标题的新数组。