Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Working Around Ionic’s Cached Views

DZone's Guide to

Working Around Ionic’s Cached Views

How to fix the default caching in Ionic using some lifecycle events.

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

Just a quick tip here as it came up in the presentation I did today – how do you handle running code when a particular view runs in Ionic? Let me begin with an example so you get what I’m talking about. 

Given a new Ionic application using the default tabs application, I’m going to modify the Account controller to add a random number to the scope:

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };

  console.log("Running stuff...");
  $scope.number = Math.floor(Math.random()*10);

})


In the view for this view I added a quick display for the number: Random number: {{number}}

iOS Simulator Screen Shot Sep 8, 2015, 2.50.52 PM

Yeah, not the most exciting demo, but you get the idea. What you’ll notice right away though is that as you click back and forth between different tabs, the value doesn’t change. And if you open up your remote dev tools, you’ll see the console message run only once.

This is due to the default caching system built into the ion-view directive. Luckily it is rather easy to fix with one of the life cycle events. The docs say you can listen for these events but don’t demonstrate how.

Here is an example:

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };

  $scope.$on("$ionicView.beforeEnter", function() {
    console.log("Running stuff...");
    $scope.number = Math.floor(Math.random()*10);
  });

})


And that’s it. For me the tricky part was $scope.$on, something I’ve not used in Angular before. You can read more about the events at the docs.

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:
ionic ,caching

Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}