2

Here is my code:

<div ng-controller="TestController">
    <h1 ng-click="click()">{{person.name}}</h1>
</div>
<script type="text/javascript">
    var app = angular.module('app', []);
    app.controller('TestController', function ($scope) {
        var p = $scope.person = {
            name: 'Br'
        };

        $scope.click = function () {
            p = {};
        }
    });
</script>

When I click on the <h1>, I reset the p object, so I expect empty in the h1 tag.

Because I think the variable p has the same reference as $scope.person, which point to the same object.

In fact nothing changed when I clicked, only if I reset the $scope.person = {}.

So why it doesn't work as I expect? What's wrong in my thought?

1
  • p is just a pointer. Physically p = {} creates object {} somewhere in memory and put in 'p' object address. Commented Mar 29, 2016 at 17:12

1 Answer 1

7

That's not related to Angular but how object are manipulated in JavaScript.

You're right when you say that p and $scope.person both reference to the same object in memory.

However when you write p = {} you are not touching the object that p was pointing to, you are having p reference a new object, hence it is not $scope.person anymore.

var a = {};
var b = a;
a === b; // true
b = {};
a === b; // false

If you want to remove the name property of p/$scope.person you can write

delete p.name; // this will also delete $scope.person.name
Sign up to request clarification or add additional context in comments.

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.