0

I asked yesterday a similar question yet there is a difference. I'm trying to create a generic function that will change a scope object(not primitive) yet it seems not to be working and I don't understand why?

My code:

webApp.controller ('VotesCtrl', function ($scope) {
    $scope.param = {name: 'Ron', age: 18};        

    change($scope.param);

    function change(contextParam) {
      contextParam = {name:'dan', age: 12};
    }
});

It seems change function does not make any change on $scope.param even though I'm passing a reference.

When I'm doing the change like the code below, it is working!

webApp.controller ('VotesCtrl', function ($scope) {
    $scope.param = {name: 'Ron', age: 18};

    change($scope.param);

    function change(contextParam) {
      contextParam.name = 'dan';
      contextParam.age = 12;
    }
});

What am I doing wrong? how can you explain this behavior?

My Plunk

1 Answer 1

0

contectParam is a reference to an object. When you use the assign operator =, you change the value of the contextParam variable - it stops being a reference to an object and takes a completely different value.

However, when you access the properties of the object referenced by contextParam, you change their values, thus making your changes be visible outside the function's scope.

As a side note, it would be much better if you did things this way:

function change() {
    return {name: 'dan', age: 12};
}
$scope.param = change();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer, another option is to use $.extend(true, configContext, {name:'dan', age: 12})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.