0

I'm working on an Ionic app that uses Angular UI Router with a Rails api backend. I've got a User model that has many Items.

When showing the User page, i'm calling Rails and returning the User along with all it's Items (so I can show them on the user's page)

Then, when I want to go to a specific Item's page, do I have to make another call to the API? I mean, I already have the item in hand. Is there a good clean way to pass the Item without having to make an api call for the specific Item?

Got any good solution for my problem?

Million thanks! Uri

2 Answers 2

1

Yes there is a perfect solution for this. Make the item page a child of your user page. When you fetch the user and items in the resolve of your state, it will be available also to all child states.

States:

$stateProvider.state('user', {
  'url': '/user',
  'controller': 'userController',
  'templateUrl': 'user.html',
  'resolve': {
    'items': [
      '$http',
      function ($http) {
        return $http.get('data.json');
      }
    ]
  }
});

$stateProvider.state('items', {
  'parent': 'user',
  'url': '/items',
  'controller': 'itemsController',
  'templateUrl': 'items.html'
});

Controllers:

angular.module('app').controller('userController', [
  '$scope',
  'items',
  function ($scope, items) {
    $scope.items = items.data;
  }
]);

angular.module('app').controller('itemsController', [
  '$scope',
  'items',
  function ($scope, items) {
    $scope.items = items.data;
  }
]);

Here the resolved items from state user can also be injected in the controller of state items.

Here's a working example on Plunker: http://plnkr.co/edit/s13BHHtVLt1sd6tFLfNW?p=preview

Nested state reference: https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views

State resolve reference: https://github.com/angular-ui/ui-router/wiki#resolve

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice! Thanks for the detailed answer!
0

Once you have your user saved with all the items, and you know that these items are not going to change, you can save the data in a Factory for the user, and then query the items accordingly without another request. Instead of the items might change you should request the items again.

2 Comments

But, you should know that doing it this way, if you refresh the page, all of that data will be gone. So you would have to either save that data to localstorage and get it out when the page loads if it exists, or get it from the server. Other things you could do also, but just be aware, you should plan for it.
Why create another dependency when ui-router already has the right functionality like nested resolves built-in?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.