Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic: Preserve $scope when navigate to another view

I'm developing an app using Ionic Framework (Angular+Cordova).

The app have a News section with a list of news loaded from a server in JSON, then I tap in a new to open the Single New's View, but when go back to the list of news, $scope has been cleared and must get again the news list from the server.

Is this the usual behavior or am I doing something wrong?

How could I prevent this behavior?

Thanks!

like image 940
Sirikon Avatar asked Jun 28 '26 17:06

Sirikon


1 Answers

You should save this kind of data in a separate service, something in the line of this:

app.service('NewsService', ['$http', function($http){
    var newsPromise;

    this.getNews = function(){
        if(!newsPromise){
            newsPromise = $http.get('news.json');
        }
        return newsPromise;
    };
}]);

app.controller('NewsController', ['$scope','NewsService', function($scope, NewsService){
    NewsService.getNews().then(function(data){
        $scope.news = data.data;
    })
}]);
like image 70
red-X Avatar answered Jul 01 '26 13:07

red-X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!