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

0

I would like to know why when I assign the value to a variable within a controller 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(',','.');

After var viagemPersistencia.valorFrete= 1500.20 and the value of $scope.viagem.valorFrete equal to 1500.20 when it could be 1,500,20 in the view, I'd like the $scope.viagem.valorFrete value not to if it changed.

Edited  The request follows part of my code so it does not extend.

Part of the 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 
  }
    
asked by anonymous 11.03.2018 / 02:42

1 answer

1

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

Making a copy without reference ( angular.copy ) creates a new object without linking to the original. So the idea would be to ensure that the content of viagem will not change after changing viagemPersistencia .

Try using angular.copy

var viagemPersistencia = angular.copy(viagem);
    
15.03.2018 / 12:33