Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass in a function (by reference) a variable in the scope

There is a way (in angularJS) to pass by reference a variable in the scope in a function (to modify it)? I've tried but the variable change doesn't happen. Here my code

$scope.modifyVar = function (myVariable){
 myVariable = 92;
}

$scope.modifyVar($scope.txtNumberOfChuck);
like image 853
Joker Avatar asked Nov 11 '14 08:11

Joker


People also ask

Can you pass a variable by reference?

Pass by reference is something that C++ developers use to allow a function to modify a variable without having to create a copy of it. To pass a variable by reference, we have to declare function parameters as references and not normal variables.

What happens if a variable is passed by reference?

Passing by reference means that the memory address of the variable (a pointer to the memory location) is passed to the function. This is unlike passing by value, where the value of a variable is passed on.

How do you pass by reference in a function?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

Can variables can be passed to a function by reference or value?

When a function is called, the arguments in a function can be passed by value or passed by reference. Callee is a function called by another and the caller is a function that calls another function (the callee). The values that are passed in the function call are called the actual parameters.


1 Answers

You cannot pass a variable by reference in Javascript. However you can pass the complete object and get your values changed.

In your case you can pass the $scope object and then modify the property value. Something like this:

$scope.modifyVar = function (myObj){
    myObj.txtNumberOfChuck = 92;
}

$scope.modifyVar($scope);
like image 57
V31 Avatar answered Oct 31 '22 06:10

V31