1

I want to unwatch one Angular scope variable after certain point in program.

Here is what I am following.

$scope.oldVar = {data: "Something"}
$scope.blankArray = []
$scope.blankArray.push($scope.oldVar)

Now whatever changes I am doing to $scope.oldVar, It is reflecting the changes to blankArray which I am viewing on Screen.

Is there any way in angular to restrict that?

Rohit
  • 337
  • 7
  • 17
  • I found some article with a workaround for your scenario: https://coderwall.com/p/d_aisq/speeding-up-angularjs-s-digest-loop – Matías Fidemraizer Apr 01 '15 at 13:38
  • 1
    This is because `oldVar` is reference type variable. And you push the reference of it to the array. You simply can do this: `$scope.blankArray.push({ data: $scope.oldVar.data })`; – valverde93 Apr 01 '15 at 13:40

1 Answers1

0

Use angular.copy

You can use angular.copy to create a new copy of the data. This would prevent the data from being bound within blankArray.

So at some point in your application, to unbind the values, you can use angular.copy.

$scope.blankArray = angular.copy($scope.blankArray)

Here Be Dragons

The problem with unbinding a value is that you'll be introducing complexity as your controller now needs to be aware of when the value is bound and when it isn't bound. This introduces an extra state to manage and all your logic now needs to have this awareness.

Demonstration

function ctrl($scope) {
    $scope.oldVar = {data: "Something"};
    $scope.blankArray = [];
    $scope.blankArray.push($scope.oldVar);
    $scope.withoutCopy = []
    $scope.withoutCopy.push($scope.oldVar);
    
    $scope.change = function() {
        $scope.oldVar.data = Math.random();
    };
  
    $scope.unbind = function() {
        $scope.blankArray = angular.copy($scope.blankArray);
    };
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="ctrl">
    <button ng-click="change()">Test</button>
    <button ng-click="unbind()">Unbind</button>
    <pre>{{ blankArray | json }}</pre>
    <pre>{{ oldVar | json }}</pre>
    <pre>{{ withoutCopy | json }}</pre>
</div>
Pete
  • 3,246
  • 4
  • 24
  • 43