A
A
Alexey Malinin2015-02-02 22:32:34
Angular
Alexey Malinin, 2015-02-02 22:32:34

Executing nested controller code after outer controller AJAX request completes?

I'm using ui-router in an Angular.JS project and the following situation has arisen:
Some controller (let's say XCtrl) is external and makes a request for JSON data using $http.get. JSON contains sections, and each section has an array of entries related to it. I need to render partitions at /x and render the entries of the partition that the user has selected at /x/:collectionid. You also need to draw a specific entry in the section at /x/:collectionid/:postid.
When I go to /x in the browser and follow the links, everything works fine. When I go to some section and refresh the page, a lot of errors fall out in the browser console related to the fact that I am trying to use data that has not yet been received (that JSON).
Temporary solution that I did: save the Promise returned from $http.get to $scope in the XCtrl controller and add more success handlers in child controllers. I believe there is a more elegant way to solve this problem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Damir Makhmutov, 2015-02-02
@amalinin

Requests to the server are better to take out in services. In general, all manipulations with data are better to take out in services. And in services already use Promise. In controllers, use promise.then()
or success, whichever is more convenient for you. This is quite normal practice.

A
Aleksei Podgaev, 2015-02-02
@alexiusp

Damir Makhmutov wrote absolutely right. In the controller - the functionality responsible for displaying data, and in services - actually receiving data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question