Petran
Petran

Reputation: 8047

Reference to a $scope array is not been updated in angularjs

I have the following code

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
$scope.people = [
    { id: 1, first: 'John', last: 'Rambo' },
    { id: 2, first: 'Rocky', last: 'Balboa' },
    { id: 3, first: 'John', last: 'Kimble' },
    { id: 4, first: 'Ben', last: 'Richards' }
];
$scope.updateByReference = function() {
  var tst = $scope.people;
  tst = [];
  console.log($scope.people);
}
});

I would expect the $scope.people to have a new value of and empty array object but it's not been updated, here is the fiddle http://jsfiddle.net/9fR23/409/

Upvotes: 0

Views: 60

Answers (2)

Ved
Ved

Reputation: 12093

 var tst = $scope.people;  //tst reference is $scope.people.

Hence any change made to tst or $scope.people will reflect to both variables.

SOLUTION:

 $scope.updateByReference = function() {
      var tst = JSON.parse(JSON.stringify($scope.people));
      tst = [];
      console.log($scope.people);
    }

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68635

Your $scope.people is an object. When you do var tst = $scope.people;, it copies the reference into the tst. After when you do tst = [], it changes the tst's value (which was the reference to the $scope.people, not the $scope.people's value). So actually when you change the variables whole value, you only set him to refer another object.

Just do

$scope.people = [];

Upvotes: 1

Related Questions