0

When passing an object to a ng-click function, the object seems to lose its reference. What is the reason?

CodePen example

<div ng-app="app" ng-controller="controller">
  <p>
    <u>Object</u> : {{ obj | json }}
  </p>
  <p>
    <button ng-click="obj = {}">obj = {}</button> <!-- works -->
    <button ng-click="voidIt(obj)">voidIt(obj)</button> <!-- doesn't work -->
  </p>
  <p>
    <button ng-click="reset()">Reset obj</button>
  </p>
</div>
angular.module('app', []).controller('controller',
function($scope) {

  $scope.voidIt = function(object) {
    object = {}
  }

  $scope.reset = function() {
    $scope.obj = { prop: "value" }
  }

  $scope.reset();

});
ryancey
  • 1,037
  • 2
  • 11
  • 27
  • What is your actual question? – Vineet Jul 08 '15 at 13:23
  • The reason is : on your `voidIt` function, your set object to {}, not `$scope.obj`. So your object is empty meanwhile `$scope.obj` remains the same. – Pierre-Alexandre Moller Jul 08 '15 at 13:27
  • @Vineet The question is: why? – ryancey Jul 08 '15 at 13:27
  • @Apédémak I get that, but shouldn't `obj`, in the view, reference `$scope.obj`? – ryancey Jul 08 '15 at 13:28
  • Everything seems to work fine. If you are wondering why pressing `voidIt(obj)` after pressing `obj = {}` doesn't do anything, it's because you are emptying your `obj` – Razvan B. Jul 08 '15 at 13:29
  • 1
    No, he's wondering why VoidIt doesn't work, EVER. It does not keep reference with the obj and object (which should reference same object) – Michael Jul 08 '15 at 13:30
  • 3
    http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Pierre-Alexandre Moller Jul 08 '15 at 13:31
  • @Apédémak As far as i understand, I can mess with `object` but shouldn't reassign it in any way (`object =` is banned) if I want to keep the reference, is that right? Edited, working example: http://codepen.io/anon/pen/WvzBWe – ryancey Jul 08 '15 at 13:44
  • That's rigth, you can modify the attribute `prop` like this : http://codepen.io/anon/pen/JdLqqO but you can't really do more by reference. – Pierre-Alexandre Moller Jul 08 '15 at 13:49

1 Answers1

0

What a nested $scope refers to can become confusing, so it's much better to use the controllerAs syntax. For a good explanation, read AngularJS 'controllerAs' vs. '$scope'.

The Codepen with ControllerAs referencing.

But if you're looking for a clear reasoning why it doesn't work, I'm lost as well. I just find it's just better to take the safer path that avoids such pitfalls.

shmck
  • 5,129
  • 4
  • 17
  • 29