Problem with Angular-material switch, when reloading it returns to its state

1

Hello, I have the following switch

html:

<div class="inset switchdemoBasicUsage" ng-controller="Movilapp" style="float:left;" ng-cloak>
     <div>
         <b>Movil:</b>
         <md-switch ng-model="data.cb2" aria-label="hola0">
             <span ng-if="data.cb2" ng-cloak>Activado</span>
             <span ng-if="!data.cb2" ng-cloak>Desactivado</span>
         </md-switch>
     </div>
</div>

Controller:

app.controller('Movilapp', function($scope, Conection, SaveCredentials) {

    $scope.data = {
        cb2: true
    };

    $scope.$watch("data.cb2", function handleFooChange( newValue, oldValue ) {
        if (newValue) {
            Conection.OnMovil({
                sucursal_id: SaveCredentials.getData().id_sucursal
            });
        } else {
            Conection.OffMovil({
                sucursal_id: SaveCredentials.getData().id_sucursal
            });
        }
    });
})

The problem:

The switch works well, the data is consumed correctly, the problem is that if I click the switch and leave it off when restarting the page or reopening it will always return the switch to activated and not like me I leave it and that I want to achieve that if I give it off, it stays there and does not make changes.

I understand that this is because I gave the variable cb1 true but I ask

How could I do it?

I have another web services that when opening the page asks for the status of the action. If you return 1 is because it is activated, if you return 0 is because it is disabled, could you do something there?

Conection.CheckMovil({
      sucursal_id: SaveCredentials.getData().id_sucursal
}, function(response){
   if (parseInt(response.activo)===0) {

   }
})

Greetings. Here is the link to my code:

link

(I do not accept stackoverflow)

    
asked by Hernan Humaña 06.10.2016 в 20:01
source

1 answer

1

Use localStorage, or ng-storage since you're using Angular

app.controller('Movilapp', function($scope, Conection, SaveCredentials, $localStorage) {

    $scope.data = {
        cb2: !!$localStorage.cb2; // Si ya lo guardaste se carga de nuevo
    };

The expression !! will convert anything to Boolean , if $localStorage.cb2 is undefined (in case it has never been executed) it will be transformed to false .

Then when you handle the Ajax call you write

$scope.data.cb2 = !!response.activo;
$localStorage.cb2 = $scope.data.cb2; // El valor se almacenará

When you update the page, the value will be restored from storage.

    
answered by 06.10.2016 / 21:07
source