0

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/

0

2 Answers 2

1

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 = [];

Sign up to request clarification or add additional context in comments.

2 Comments

So how can I achieve the desired behaviour ?
@Petran Updated
0
 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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.