0

I have a scope variable, $scope.test. If I pass this variable in a function that is invoked in a template as an argument and then I try to change it in the controller, it seems that the original $scope.test does not change. Only the local variable, foo changes. But isn't foo a reference to $scope.test?

var mod = angular.module('app', []);

mod.controller('myCtrl', function($scope) {
  $scope.test = 'test';

  $scope.doSomething = function(foo) {
    foo = 'scope.test should change';
  }
})

Here, I'm passing test to the doSomething function which is in the controller above.

  <body ng-app='app'>
    <div ng-controller='myCtrl'>

      <button ng-click="doSomething(test)">testing</button>  

      <h1>{{test}}</h1>

    </div>
  </body>

Here's the plunker: http://plnkr.co/edit/JBsos0qVJP47WgfD9Fee?p=preview

sq1020
  • 1,000
  • 2
  • 9
  • 15

1 Answers1

3

This is indeed something that you might want to do within Angular.js. However, in your case, you are passing a primitive string, which is passed by value instead of by reference in JavaScript. You can pass objects and change the properties of the objects, but when you pass primitives, they are not mutable. This is also a reason why one of the best practices for Angular.js is that any bindable items have a ., which is automatically a property of an object.

http://docstore.mik.ua/orelly/webprog/jscript/ch11_02.htm

Claies
  • 22,124
  • 4
  • 53
  • 77
  • I'd never used this myself, but tried what Andrew mentioned and it seems to work: http://plnkr.co/edit/FByCft2Pmgo2dOI4k7eY?p=preview – Nicholas Hirras Jan 30 '15 at 21:24
  • Ah, of course! I knew I had accomplished something similar before but didn't realize that it always with objects which as you mention are passed by reference. – sq1020 Jan 30 '15 at 22:14