Jasmin Kurtic Jasmin Kurtic - 3 months ago 15
Javascript Question

Difference when pass primitive types and Objects to Conntrollers

I'm post example, because i'm thinking you are easier understand my question.

I have this HTML markup

<div ng-app="autoDrops" ng-controller="testController as test">
<div ng-controller="simpleController as simple">
<a href="" ng-click="test.addValue(value, test.testValue)">Add</a>
<a href="" ng-click="test.addValue2(value2, test.testValue2)">Add2</a>
</div>
<a href="" ng-click="test.addValue(value, test.testValue)">Add</a>
<a href="" ng-click="test.addValue2(value2, test.testValue2)">Add2</a>
<p>
{{test.testValue}}
</p>
<p>
{{test.testValue2}}
</p>
<div>


and my AngularJs controllers defined like this

var autoDrops = angular.module('autoDrops', []);
autoDrops.controller('testController', function ($scope) {
this.testValue = 0;
$scope.value = 1;
this.addValue = function(value, testValue){
//why function not work, if i remove this?
testValue = testValue + value;
}
$scope.value2 = {value:"1"};
this.testValue2 = [];

this.addValue2 = function(value, testValue2){
//this function work with this?
testValue2.push(value);
}
});
autoDrops.controller('simpleController', function ($scope) {
$scope.value = 1;
$scope.value2 = {value:"1"};
});


Example you can see jsfiddle

Answer

As said @MMHunter this is because in the 1st case you passe a simple value whereas in the secnd case, you pass an array.

Array are passed by reference and value are passed by value.

So if you want to make it works change

  1. this.testValue = 0; to this.t = {testValue : 0};
  2. test.addValue(value, test.testValue) to test.addValue(value, test.t)
  3. And...

this.addValue = function(value, testValue){
  //why function not work, if i remove this?
  testValue = testValue + value;
}

To

this.addValue = function(value, t){
  //why function not work, if i remove this?
  t.testValue = t.testValue + value;
}