【发布时间】:2018-02-28 22:33:49
【问题描述】:
AngularJS 还是新手,我正在尝试从数组中格式化我的响应数据。
据我了解,它应该是一个非常简单的概念,您循环访问 response.data 对象集并访问对象内的 item.properties,它会将数据作为字符串返回。
我的问题是它似乎没有将其作为字符串返回,而是作为对象值(?)返回。
最好用一个例子来说明。数据是从我的本地 solr 实例中提取的,仅供参考。
相关 html:(循环)
<div ng-repeat="item in vm.items | filter:philter">
<span class="item trim"><a href='{{item._name}}' alt='{{item._name}}'>{{item._name}}</a><br />{{item._content}}</span>
</div>
控制器
app.controller('searchBtnCtrl', ['$scope', '$http', 'PagerService', function ($scope, $http, PagerService) {
var vm = this;
$scope.performSearch = function () {
console.log('clicked');
$('.item').remove();
$http.get('http://localhost:8984/solr/index/select?q=_content:' + $scope.searchInput + '&fl=_name,_content,_fullpath&omitHeader=true&rows=10000&wt=json').then(function (response) {
$scope.responseData = response.data.response.docs;
vm.resultCount = response.data.response.docs.length;
vm.itemsToDisplay = $scope.responseData; // array of items to be paged
vm.pager = {};
vm.setPage = setPage;
initController();
function initController() {
// initialize to page 1
vm.setPage(1);
}
function setPage(page) {
if (page < 1 || page > vm.pager.totalPages) {
return;
}
// get pager object from service
vm.pager = PagerService.GetPager(vm.itemsToDisplay.length, page);
// get current page of items
vm.items = vm.itemsToDisplay.slice(vm.pager.startIndex, vm.pager.endIndex + 1);
}
});
}
}]);
控制台输出(分页返回正确数量的对象)
Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 3 more… ]
单击数组中的第一个对象有以下输出:
_content:Array[1]
_fullPath:/path/to/file
_name:Array[1]
_proto_:Object
...然后展开_name数组:
0:"Name of first item"
length:1
我期待的是 div 将包含字符串形式的项目名称和内容。
我得到的是正确的数据,只是包含在 [" "] 中。 例如。
意外结果
<div>
["P4P Correspondence"]
["P4P Correspondence \nPay for Performance (P4P) \nIEHP will keep you informed of past....
我可以在表达式中做些什么来让它去掉左括号/引号吗?
谢谢!
【问题讨论】:
-
从localhost:8984/solr/index/select?q=_content:...上的 GET 调用返回的 JSON 是什么样的?
-
让我用该信息更新我的问题。 :)
-
似乎您需要在 ng-repeat 中更深入地了解 JSON。即 {{item._name[0]}} 或类似的东西。如果展开 _name 数组,它是什么样子的?
-
我可以在表达式中这样做吗?我不确定如何将 [i] 类型的变量添加到表达式中。我会根据您的新请求更新问题。
-
哇,就是这样.. 只需添加 [0] 就可以了.. 你这个人 Carlo!非常感谢! :)
标签: angularjs angularjs-directive angularjs-ng-repeat