Alan2
Alan2

Reputation: 24572

Can I create a reference to a variable in javascript?

I tried the following:

    $scope.qs = {};
    $scope.qh = {};
    $scope.qv = {};
    var qs = $scope.qs;
    var qh = $scope.qh;
    var qv = $scope.qv;
    $scope.getQuestionHeaders = function () {
        var url = '/api/Test/GetQuestionHeaders?id=1';
        $http.get(url)
            .success(function (data, status, headers, config) {
               qh = data.testQuestionHeaders;
               qs = qh[0];

My data is assigned to qs and I can see additional fields such as qs.i, qs.q etc. But when I use the chrome developer tools I notice that nothing has been assigned to $scope.qs

Upvotes: 0

Views: 62

Answers (2)

user1636522
user1636522

Reputation:

You are overriding the variables qh and qs, so they loose their previous references. You have to do this if you want to keep both vars synchronized :

$scope.qh = qh = data.testQuestionHeaders;
$scope.qs = qs = qh[0];

Updating properties doesn't affect variables references :

qh.witness = true;
$scope.qh.witness === qh.witness === true; // true

Upvotes: 1

Evan Trimboli
Evan Trimboli

Reputation: 30082

That's correct.

You're essentially doing:

foo.someProp = 1;
var bar = foo.someProp;
bar = 3; 

Would you expect foo.someProp to be 3? If you want to update the $scope.qs reference, then you need to do it directly, otherwise you're just changing a local variable reference. You can modify items inside qs:

qs.foo = 1;
console.log($scope.qs.foo);

Upvotes: 1

Related Questions