Pexilius Pexilius - 6 months ago 16
AngularJS Question

Load json by latest input - Angularjs

I'm building an app where the user gets to see his newest posts on his profile, currently I'm loading in the jsons going through the list from top to bottom.

Is there an easy way to switch this around, in other words load the newest inputs, this way it can show the 'recent activity'.

This is my code to get the current data:

$http.get('URL')
.then(function(result) {
angular.forEach(result.data, function(data, key) {
if(data.userId === authenticated.profile.user_id) {
$scope.posts.push(data);
}
});
});

Answer

It depends on how are you using the array of datas in your view , you can use filter in angularJs to show the recent data based on the timeStamp or based on your requirement ,

Instead of using push method you could use unshift to add the data from the beginning of the Array.As a result new data will be at the first data item in the array as below

 angular.forEach(result.data, function(data, key) {
                if(data.userId === authenticated.profile.user_id) {
                    $scope.posts.unshift(data);
            } 

If your data has timeStamp you can sort data based on that using filter as below

template

<div ng-repeat="post in posts | orderBy :'created_at':true "></div>

refer : orderBy