1

Fiddle: http://jsfiddle.net/RnJbt/2/

I have a template block, where I initiate a local model, which is not really important to be included in the namespace, but is useful for the template's scope. The model is passed to a function when user clicks on a button. The function should update the value of the model.

Fiddle shows that the model "deneme" does not change when passed as an argument to update function. But I can update the value in the "update" function if I access the model via the $scope object as given below.

...controller...
    $scope.update = function(val){
        val = 10; // does not update deneme 
        $scope.deneme = 34; // updates it as expected
    }   

I don't want to pollute the controller's namespace with throwaway model names that are only useful for the template blocks they are initiated. How can i process almost anonymous arguments within controller scope without having to declare them by their names?

Gray
  • 7,050
  • 2
  • 29
  • 52
altunyurt
  • 2,821
  • 3
  • 38
  • 53

1 Answers1

1

It is because it is a primitive value. I changed the fiddle a little bit, like this, and it works as you expect:

ng-init="deneme = {value: 5}"

$timeout(function(){
val.value = 23;
.....

It is the same as if you set any javascript variable to a primitive, and then set another variable to that value, and then reset the original variable.

var a = 10
var b = a
var a = 2
// a = 2, b = 10

I ran into this same issue a couple months ago, so it is still fresh in my mind.

Ryan Quinn
  • 1,175
  • 1
  • 15
  • 28
  • thanks for the reply and information about the primitives. I went on and made a quick search oh the topic and found this: http://stackoverflow.com/a/509614/37491 . It seems that both val and deneme are pointers to primitives, and assigning val = new_val only changes the point where it points to. but assigning val.value = new_val updates the "value" pointer of the object which both val and deneme points to. Thanks for the enlightenment :) – altunyurt Jul 26 '13 at 20:27