Maintain boolean toggle state when navigating in angularjs
I have a checkbox that toggles an image in a list box in angularjs. The switch shows images when pressed. However, when I navigate to other views and then return to the list view, the toggle state for the images is not checked.
List view
<input type="checkbox" ng-click="vm.toggleImage()">
List
<td ng-if="vm.showImage">
<img ng-src="{{task.imageUrl}}" class="img-responsive img-thumbnail img-circle" />
</td>
controller
// Show Image
vm.showImage = false;
vm.toggleImage = function () {
//Inverse Boolean
vm.showImage = !vm.showImage;
}
Page updates are not refreshed during navigation.
How do I save images while the user navigates back and forth through the SPA?
One way to solve this problem is to store your state / model in the service.
then you can inject it wherever you need it:
ItemController.$inject = ['Items'];
function ItemController (Items) {
var vm = this;
vm.items = Items;
}
the service is singleon. This is a fantastic way to say its object, which persists for the entire time the program is active.
An item service might look something like this:
function Items () {
return [
{name: 'test1', on:true},
{name: 'test2', on:true},
{name: 'test3', on:false},
{name: 'test4', on:true},
{name: 'test5', on:false},
];
}
You can see this in action in the next plunk you can click on any of the items and change their on / off state. then click login to start another route, there is a link that will take you back. the state will remain unchanged and the controller will be recreated.
Feel free to ask if you have any further questions about this!