AngularJS: keep state of input checked after change view

Viewed 51

The site I am working on displays news in one of two ways: list or grid view.

The default mode is list. The user can change the mode through options located at the top:

enter image description here

The options are in a div and a label:

<div class="btn-group" data-toggle="buttons" id="view-card-mode" data-intro="{{uikey.chTipoVista}}" data-position="bottom">
  <label class="btn btn-default grid-view" title="{{uikey.VistaGrilla}}">
    <input type="radio" name="options" id="grid-view" autocomplete="off" checked>
    <i class="fa fa-th"></i>
  </label>
  <label class="btn btn-default list-view active" title="{{uikey.VistaLista}}">
    <input type="radio" name="options" id="list-view" autocomplete="off">
    <i class="fa fa-list"></i>
  </label>
</div>

But in the controller of this page there is no reference to these controls. The change in the view is made through jquery:

// List/Grid View
$('#view-card-mode .list-view').off('click');
$('#view-card-mode .list-view').on('click', function() {
  $('.card-container').addClass('card-list');
  $('.card-container').removeClass('card-grid');
  $('.actions-list').show();
  $('.actions-grid').hide();
});

$('#view-card-mode .grid-view').off('click');
$('#view-card-mode .grid-view').on('click', function() {
  $('.card-container').removeClass('card-list');
  $('.card-container').addClass('card-grid');
  $('.actions-list').hide();
  $('.actions-grid').show();
});

So, when I click on "grid view icon", the function add a class "grid" on the following div(by default is list view):

<div class="card-container card-list" id="menucontext">

The problem is If I select "grid view", when i change the state of the page (for example, i visit a news and then go back), the selection is gone, always return to list view (the default)

Is there any way I can keep the view selected via angularjs or jquery? I have little experience with angularjs and I am still trying to undertand the logic behind data binding.

I searched other similar questions but nothing worked. I have even tried to convert the jquery function into angular but I am not sure how to bind then into the html:

Controller First try:

$scope.view = 'card-container card-list';
$scope.viewTypeSelected = "list";

$scope.changeView = function() {
  if ($scope.viewTypeSelected === "list") {
    $scope.view = 'card-container card-grid';
  } else {
    $scope.view = 'card-container card-list';
  }
}

Controller Second try:

$scope.viewTypesCtrl = function() {
  var self = this;
  self.views = ["card-grid", "card-list"];
  self.changeView = changeView;

  function changeView(view) {
    self.viewSelected = view;
  }
}

I need to clarify that the site works normally, there are no problems. I just have to add this functionality.

Thanks in advance.

0 Answers
Related