Ionic: keep $ scope value when switching to another view
I am developing an application using Ionic Framework (Angular + Cordova).
The app has a news section with a list of news loaded from the server in JSON, then I use a new one to open a Single New View, but when I go back to the news list, the $ scope has been cleared and should get the news list from the server again.
Is this normal behavior or am I doing something wrong?
How can I prevent this behavior?
Thank!
You have to store this kind of data in a separate service, something on the line:
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;
})
}]);
You can also use $rootScope
. As Onosa mentions in the comments, every time you create a new controller a new variable is introduced $scope
, but $rootScope
(as the name says) persists for the life of your application (it's global).