0

How to pass a reference of scope's model to a function, where I can edit the contents of it?

For example, I have controller like this:

app.controller('MyController', function ($scope) {
    $scope.magic = 123;

    $scope.someMethod = function(model) {
        model = 321;
    }
});

And a view:

<div data-ng-controller="MyController as ctrl">
    ...

    <input type="text" data-ng-model="magic">

    <button type="button" data-ng-click="someMethod(magic)">
</div>

Now when I click the button, it almost works, but after someMethod, the actual $scope.magic has not changed, it's still 321. So apparently someMethod creates a copy of the model, not reference. How to get the reference instead?

nhaa123
  • 9,570
  • 11
  • 42
  • 63
  • 1
    The problem is that you're passing a primitive to the function and then merely overwrite the variable. This is not going to reflect on the outside world at all. Try making `magic` an object and modifying one of its properties... – deceze Jun 03 '15 at 12:11
  • You're passing a primitive in, so it's pass by value. Pass in an object to get pass by reference. But in either case, why not just update `$scope.magic` in `someMethod`? – CodingIntrigue Jun 03 '15 at 12:11
  • _Always_ have a `.` in your models: https://github.com/angular/angular.js/wiki/Understanding-Scopes and https://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m – JAAulde Jun 03 '15 at 12:13
  • deceze, thanks. That was the thing. Put that as an answer and I'll mark it. – nhaa123 Jun 03 '15 at 12:18

1 Answers1

0

Change your someMethod to the following:

$scope.someMethod = function(model) {
    model.magic = 321;
}

// Or accepting a new value
$scope.anotherMethod = function(model, value) {
    model.magic = value;
}

HTML:

<input type="text" data-ng-model="model.magic">
<button type="button" data-ng-click="someMethod(model)">Do Some Magic!</button>

<!-- Or with passing a new value -->
<button type="button" data-ng-click="anotherMethod(model, '123')">Do Some Magic!</button>

JSFIDDLE

devqon
  • 13,818
  • 2
  • 30
  • 45
  • But then I'm bound to use only magic-property. I need it to be what ever variable what's passed in the function. – nhaa123 Jun 03 '15 at 12:15