Avatar of chand pb
chand pb
Flag for United States of America asked on

how to do Asynchronous loading--javascript/Angular..

  Not sure how to do this...need some advise/ snippet/links ..

Have  a list of names on the server..I created  a Page that has a button "load more"...

When the user access the page . I would like following

1: call the APi to bring back 40 record ( have this logic)
2: Only display 20 records on the UI
3: When the user press the button "load more". I would like to
   A: Load the next 20 record (that was retrieve above) and render it in UI
   b: Make an Async call to get the next 20 record and keep it in memory

4: #3 continue as long as their are records or user stop pressing the "load more" button,,

Thanks for your help..

Avatar of undefined
Last Comment
Alexandre Simões

8/22/2022 - Mon
chand pb

here is an example I saw that has the load more concept --http://jsfiddle.net/api/post/library/pure/

but it does not pre-load the next batch of data....
Alexandre Simões

(your link points to an empty jsfiddle)

This is more of less the same as the infinite scroll technique, where the user can scroll down a list and when is almost reaching the end, a new batch of records gets added to the list.

In your case you should have a (angularjs) factory that isolates this logic.
In this factory you should keep the list in memory, that will start with the initial 40 items and the next will be added to it.
In this same factory you must have a method called getNextPage that implements the paging logic you described.
The main idea is:
    - if the items list is empty, get the double of the page size starting from the beginning
        > get the first [pagesize] elements in the list
        > track the index of the last item retrieved (it might have been less than 20)
        > if you got less than [pagesize] is because your in the last page. You can use this information to avoid useless calls to the server and potentially disable the "Get More" button.
    - if the items list have elements, pick [pagesize] elements
       > if you gor [pagesize] elements, do the ajax call to get [pagesize] more
       ... behave like above, tracking the last item index

If you know how to do this without the pre-fetching logic, adding it is quite easy.
chand pb

Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Alexandre Simões

View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.