Ionic: Preserve $scope when navigate to another view

爷,独闯天下 提交于 2019-12-10 18:36:36

问题


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!


回答1:


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;
    })
}]);



回答2:


You can also use $rootScope. As Onosa mentioned in the comments, every time you instantiate a new controller a new $scope variable is injected in, but the $rootScope (as the name says) keeps preserved for the whole life of your app (it's global).



来源:https://stackoverflow.com/questions/25568057/ionic-preserve-scope-when-navigate-to-another-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!