I have a checkbox that toggles an image in a list in angularjs. The toggle shows images when clicked. However when i navigate to other views and then return to the list view the toggle state for the images is unchecked.
List view checkbox
<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;
}
There are no page refreshes during the navigation.
How do i keep the images showing as the user navigates back and forth through the SPA?
One way to solve this is to keep your state/model in a service.
then you can inject it where you need it like this:
ItemController.$inject = ['Items'];
function ItemController (Items) {
var vm = this;
vm.items = Items;
}
a service is a singelon. That's a fancy way to say, its an object that gets retained during the entire time the program is active.
The item service can 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 following plunk you can click on any of the items and change their on/off state. then click the log on button to trigger another route, there is a link in there that will take you back. the state will stay the same, while the controller will be recreated.
Don't hesitate to ask if you have further questions about this!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With