0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.