通过数组的AngularJS 1.6返回对象数据

问题描述 投票:0回答:2

对于AngularJS来说还是新手,我正在尝试从数组中格式化我的响应数据。

据我所知,它应该是一个非常简单的概念,你遍历一个response.data对象集并访问对象中的item.properties,它将以字符串形式返回数据。

我的问题是它似乎没有将它作为字符串返回,而是作为对象值(?)。

最好的例子说明。数据是从我当地的solr实例中提取的,只是fyi。

相关的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.... 

我还能在表达式中做些什么来去除开头和结束括号/引号吗?

谢谢!

angularjs angularjs-directive angularjs-ng-repeat
2个回答
1
投票

更好的解决方案是在返回ajax调用时完成它:

vm.itemsToDisplay = $scope.responseData;
vm.itemsToDisplay = vm.itemsToDisplay.map(function(item,index){
   return item[0];
});

这样你就不再需要在你的html上添加所有“[0]”concat了。


0
投票

感谢Carlo,解决方案非常简单。

我只需要在我的数组中深入挖掘并在表达式中添加[0]。

所以完整的解决方案看起来像:

<span class="item trim"><a href='{{item._name[0]}}' alt='{{item._name[0]}}'>{{item._name[0]}}</a><br />{{item._content[0]}}</span>

谢谢卡罗!工作得很完美。 :)

© www.soinside.com 2019 - 2024. All rights reserved.