How to use ng-change to control a toggle

1

It turns out I have a switch from the Angular Bootstrap Toggle library and I need to control its function using ng-change .

In my html I have the switch as follows:

<toggle ng-model="ValueResponse" ng-change="changed()" on="Enabled" off="Disabled"></toggle> :Movil.

ValueResponse corresponds to the function that indicates the state of the mobile, that is, if it is active or inactive

Conection.CheckMovil({
    sucursal_id: SaveCredentials.getData().id_sucursal
  }, function(respuesta) {

      var data = JSON.parse(JSON.stringify(respuesta));
      var activo = data.activo;

      if(activo == "1"){
          $scope.ValueResponse = true
      } else {
          $scope.ValueResponse = false
      }
});

Now I need to control the function change()

The request to activate:

$scope.changed = Conection.OnMovil({
    sucursal_id: SaveCredentials.getData().id_sucursal
}, function(response){

});

The request to deactivate:

$scope.changed2 = Conection.OffMovil({ 
    sucursal_id: SaveCredentials.getData().id_sucursal
}, function(response){

});

Then with ng-change I can put only one and when activating and deactivating it will always be executed ... how do I solve it? or how can I implement the code?

    
asked by Hernan Humaña 26.10.2016 в 21:20
source

1 answer

2

You do not need to use ng-change to control this. This directive is designed to work on input elements and you are using a directive called toggle .

It's very easy to write anyway

$scope.$watch('ValueResponse', function(val) {
    if (!angular.isUndefined(val)) {
        if (val) {
            Conection.OnMovil({
                sucursal_id: SaveCredentials.getData().id_sucursal
            }, function(response){
                // callback
            });
        } else {
            Conection.OffMovil({ 
                sucursal_id: SaveCredentials.getData().id_sucursal
            }, function(response){
                // callback
            });
        }
    }
});

since that directive is binding with the value of 'ValueResponse' in your model.

Keep in mind that if the user activates / deactivates very quickly you will be making a lot of consecutive ajax calls, so I recommend you do a throttle .

    
answered by 26.10.2016 / 21:46
source