Note that there are some explanatory texts on larger screens.

plurals
  1. POng-init + ng-controller: strange behavior in the controller's scope
    primarykey
    data
    text
    <p>I'm new to Angular but really enjoying its approach. I have an HTML file where I am initializing a variable with <code>ng-init</code> in a <code>&lt;div&gt;</code> element, where I'm also declaring a controller with the <code>ng-controller</code> directive:</p> <pre><code>&lt;div ng-controller="myCtrl" ng-init='foo="bar"'&gt; </code></pre> <p>If I <code>console.log</code> the <code>$scope</code> object from the controller script I can see the <code>foo</code> property listed among the others, but when I try to access it from the same script it gives me <code>undefined</code>. I'm also using <a href="https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk?hl=en" rel="nofollow noreferrer">Batarang</a> and it shows me a model for the <code>&lt;div&gt;</code>-scope that also includes the <code>foo</code> property.</p> <p>I know from the second answer to <a href="https://stackoverflow.com/questions/11703477/pass-variables-to-angularjs-controller-best-practice/13075627#13075627">Pass variables to AngularJS controller, best practice?</a> that I can solve the problem by moving my <code>ng-init</code> directive into an outer <code>&lt;div&gt;</code>, but I would like to know what is really going on here behind the scenes. Any help greatly appreciated, thanks in advance.</p> <h2>EDIT</h2> <p>The order of the directives in the <code>div</code> element does not matter. The problem is still there even if <code>ng-init</code> is specified before <code>ng-controller</code></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload