user3841621
user3841621

Reputation: 140

Variable visible in $scope but undefined when actually accessed in Angular

In Angular, I have a variable var1 which is defined in an ng-init (I am aware that this isn't recommended practice).

From my controller, if I do console.log($scope), I can see the variable var1 with its initialised value. If I console.log($scope.var1), I find that it is undefined

app.controller('app', function($scope) {
    console.log($scope); // var1 appears here with it's initialised value
    console.log($scope.var1); // this is undefined
});

Why might the first log show the initialised variable but the second not?

----- EDIT ------

Note if I do

setTimeout(function() {
    console.log($scope.var1);
}, 0);

then var1 is defined.

Upvotes: 0

Views: 496

Answers (1)

Manish Kr. Shukla
Manish Kr. Shukla

Reputation: 4477

This might be occurring because you're trying to access the variable even before it's assigned a value by angular.

  1. try putting your console statement in a timeout.

  2. Avoid using ng-init for initializations.

Upvotes: 2

Related Questions