if I pass a variable in $ scope to a service, if it is modified in the service, is it not modified in the controller?

0

Good morning,

I am doing this procedure and I have a question, I am passing a series of paramentos to a service, that in the modification I modify those variables that go by parameter, then when entering in the controller, I do not see the changes, eye this happens nothing else with variables that are not an array, I leave the code:

Controller:

gridService.potitionInitial($scope.grids, $scope.posXAct, $scope.posYAct);

Service:

this.potitionInitial =  function (grid, posXAct, posYAct) {   
                posXAct = Math.floor(Math.random()*10);
                posYAct = Math.floor(Math.random()*10);
                grid[posXAct][posYAct].active = true;
            }

The $ scope.grid if it is modified, but the $ scope.posXAct and $ scope.byYAct no, I do not really understand why the arrays are passed by reference and the normal variables do not, please help me, I urgently need to solve this.

Greetings

    
asked by Carlos Aguilera 23.04.2017 в 09:48
source

1 answer

1

When you pass a variable as a parameter to a function, it is passed by value (by value) but when it is an object it is passed by reference but only the properties of the object can be modified

Example :

function prueba(a, b)
{
  a.b = "adios";
  b.c = "adios";
  a = null;
}

var a = {
  b : "hola"
};

var b = {
  c : "hola"
};

prueba(a,b);

console.log(a)
console.log(b)

Print:

[object Object] {
  b: "adios"
}
[object Object] {
  c: "adios"
}

If you look at the internal properties if they were modified but not the object as such, it happened with a = null . The object a still has its property although we assign null at the end of the function.

    
answered by 24.04.2017 / 21:37
source