0

I'm trying to assign a variable to another variable and try to do only one way binding. But when value is updated in view, it updates to original variable too. How do I stop this two way binding while assigning variable to another.

For example:

function personController ($scope) {
    var templateValue= "original value";

    $scope.myVal= templateValue;
}

In view:

<input type="text" ng-model="myVal" />

Result:

When we type something in textbox, it updates value in myVal and templateValue too, i.e value in templateValue changes to whatever I just typed in the input box. Is there a way to assign variable to another variable doing only one way binding? I want two way binding between $scope.myVal and the input box but not between templateValue and input box.

Dennis Kriechel
  • 3,719
  • 14
  • 40
  • 62

1 Answers1

5

You can't "force one-way binding" because of the weay JavaScript works.

In your example, updating myVal will not actually update templateValue.

function personController($scope) {
    var templateValue = "original value";
    $scope.myVal = templateValue;
}

If you have the following structure, then yes, changing myVal.test will update templateValue.test because they both reference the same object in memory.

function personController($scope) {
    var templateValue = { test: "original value" };
    $scope.myVal = templateValue;
}

if you want myVal and templateValue to reference different objects but have the same content, make a copy of the original object:

$scope.myVal = angular.copy(templateValue);

I also suggest familiarising yourself with Javascript by reference vs. by value.

Community
  • 1
  • 1
user2943490
  • 6,900
  • 2
  • 22
  • 38