简体   繁体   中英

AngularJs - data not showing in ng-repeat

I am trying a simple Spring MVS AngularJs REST application. All I am doing is fetching a list of customers from the database and passing it to the AngularJs controller.

In the AngularJs controller, while logging, I can see the promise and the data come through but for some reason the ng-repeat in the view does not pick it up. What am I doing wrong?

Spring Controller.. .

@RequestMapping(value = "/cust_list", method = RequestMethod.GET)
public ModelAndView getAllCustomers(Model model) {
    return new ModelAndView("cust_list", "listCustomers", getCustomers());
}

Angular...

angular.module('lilmoApp', ["ngResource"])

// service
.factory('CustomerService', ['$resource', function($resource) {
    return $resource('/lilmo/cust_list').get();
}])

//controller
.controller('CustomersListController', ['$scope', '$resource', 'CustomerService', function ($scope, $resource, CustomerService) {
    $scope.customers = [CustomerService] 
    console.log($scope.customers);
}]);

HTML view...

<table class="table table-bordered table-striped">
    <tbody>
        <tr ng-repeat="customer in customers">
            <td>{{customer.firstName}}</td>
            <td>{{customer.lastName}}</td>
        </tr>
    </tbody>
</table> 

This is the javascript console with the data...

在此处输入图片说明

Though the data is coming through, it does not show up in the view, using the ng-repeat . Any help is appreciated. Thanks in advance.

It looks like your api result puts the customers inside a listCustomers child. This is useful because the $resource object attaches promise related fields to the root, so putting the actual data on a child makes it more clear. With that in mind, try this in your html:

<tr ng-repeat="customer in customers.listCustomers">

It just looks like the ng-repeat is referencing the wrong array.


Update, as Johan said, you are placing the service into an array, so your $scope assignment needs to be updated as well by removing the unnecessary brackets.

the other answer is almost the solution BUT you are setting

$scope.customers = [CustomerService]; 

so its a array and index 0 is CustomerService you could set as

$scope.customers = CustomerService; 

and use

<tr ng-repeat="customer in customers.listCustomers">

otherwise without changes use

<tr ng-repeat="customer in customers[0].listCustomers">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM