Assign value to a variable in a controller and do not modify the value of the $Scope variable

Asked

Viewed 555 times

0

I wonder why when I assign the value to a variable within a controller coming from a $Scope variable and change the value of that variable, the value of the $Scope variable is also changed. For example:

$scope.viagem.valorFrete = 1.500,20; 
var viagemPersistencia.valorFrete = $scope.viagem.valorFrete.replace('.','').replace(',','.');

Afterward var viagemPersistencia.valorFrete= 1500.20 and the value of $scope.viagem.valorFrete equal to that 1500.20 when it might be 1,500.20 in the view, I would like the value of $scope.viagem.valorFrete did not change.

Edited The request follows part of my code not to extend.

Part of html:

<input id="freteviagem" maxlength="9" type="text" name="freteviagem" ng-model="viagem.valorFrete">
      <div id="btn-salvar" style="text-align:right;">
      <button type="button" class="btn btn-primary" ng-click="salvar(viagem)">
          <span class="fonte-viagem">Salvar</span>
      </button>
</div>

Controller:

  $scope.salvar = function(viagem) {
     var viagemPersistencia = viagem;
     viagemPersistencia.valorFrete = viagemPersistencia.valorFrete === 
     undefined || viagemPersistencia.valorFrete === null ? null 
     (viagemPersistencia.valorFrete + "")
     .replace('.','').replace(',','.');
    //VALOR $scope.viagem.valorFrete é o mesmo de viagemPersistencia.valorFrete neste momento 
  }
  • It would be interesting for you to exemplify with code, so I can answer you precisely.

  • You need to clone the object instead of assign.

  • Var x = angular.copy(y)... if I am not mistaken it is so.

  • Edson Alves worked out as you commented following example , but why does it happen? and apparently only with objects.

1 answer

1

In Javascript variables are passed by reference, then if the variable viagemPersistencia the saved copy of viagem will also be impacted.

Making a reference copy (angular.copy), a new object is created with no link to the original. So the idea would be to ensure that the content of viagem will not change after changing viagemPersistencia.

Try to use angular copy.

var viagemPersistencia = angular.copy(viagem);
  • Thanks for the tip!

  • Lucas Duarte - I had forgotten the detail of variables of the object type passed as reference, in this case it is because the variable is of the object type, because if it was of the primitive type it would not happen the same. Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.