One way data binding inside ng-click

Issue

I have two $scope array inside my controller.

$scope.arrayA= [false, false, false, false, false, false];
$scope.arrayB= [false, false, false, false, false, false];

arrayA will change depends on checkbox click. I have done this part.

arrayB will change values to be equal to arrayA only when a button is clicked.

<button type="button" ng-click="arrayB = arrayA" class="btn btn-search">Get Data</button> 

The problem is once the button is clicked, two way data binding is implemented. arrayB will change everytime arrayA changes.

I only want arrayB to change when the button is clicked. Is there a way to use the angular one-way data binding @ inside ng-click? You know like how we pass variables values in python as varB = varA.

Solution

Instead of assigning arrayA directly to arrayB, you need to create a copy of it, so that both variables don’t refer to the same object.

arrayA = arrayB

The above assignment simply makes arrayA and arrayB to refer to the same object. On click of the button, you may try this:

arrayB = arrayA.map(item => item);

This will ensure that a new copy of the array is created, and since the values varA contains are primitive (boolean), there will be no conflicts.

Answered By – 31piy

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.