JS-Data loads data but doesn't render in view

111 Views Asked by At

I have followed the js-data angular tutorial to setup js-data-angular in my current project.

model definition:

     .factory('shipmentFactory',
    function(DS) {
      return DS.defineResource({
        name:'ShipmentInstructions',
        idAttribute:'id',
        basePath:'apiEndpoint'
      }
        );
    }).run(function (shipmentFactory){})

In my controller:

.controller('ShipListCtrl', function($scope,shipmentFactory) {
    shipmentFactory.findAll().then(function(shipmentInstructions){
      $scope.shipments = shipmentInstructions;
      console.log($scope.shipments)
    });
});

In my view i attempt to iterate over the returned object using ng-repeat but nothing is displayed. I know that my endpoint is hit and data is returned because my console displays the returned shipment object.

The tutorial mentions how to load data into the views but looks to be for those using ngRoute. I am using ui-router in my current project and ran into more challenges when I tried to resolve that resource in that state.

That resource is used in a view that is included in another view - the template view for the state.

Just looking for some direction on how to get my data to display in my view please and thank you in advance.

Revised shipment model:

  .factory('shipmentFactory',
    function(DS) {
      return DS.defineResource({
        name:'ShipmentInstructions',
         idAttribute:'id',
            basePath:'apiEndpoint',
        cacheResponse: true,
        afterFindAll: function(data, cb){
          //extract the array from that nested property
          shipmentsArray = [];
          //forloop to push every item returned to
          for(var i = 0; i < data.shipmentInstructions.length; i++ ){
            shipmentsArray.push(data.shipmentInstructions[i]);
          }
          cb(null,shipmentsArray)
        }
      }
        );
    }).run(function (shipmentFactory){})/*makes sure shipmentFactory gets defined*/
1

There are 1 best solutions below

1
On BEST ANSWER

Your array of shipment instructions is nested under a "shipmentInstructions" property, but by default js-data expects the data itself to be the array.

You need to extract the array from that nested property. Something like an afterFind or afterFindAll hook would be a good place to do that. See my answer to another StackOverflow question.