What is the scope of ng-init in Angular? Here's a simple example that demonstrates my question:
<div ng-init="model = { year: '2013'}">
<a href="" ng-click="model.year = '2012'">2012</a> |
<a href="" ng-click="model.year = '2013'">2013</a>
<div>Showing {{ model.year }}</div>
<hr />
</div>
<div ng-init="model = { year: '2013'}">
<a href="" ng-click="model.year = '2012'">2012</a> |
<a href="" ng-click="model.year = '2013'">2013</a>
<div>Showing {{ model.year }}</div>
</div>
Live example available here: http://plnkr.co/edit/HkioewOzzglvFMKDPdIf?p=preview
Is seems that ng-init scope is shared among the 2 div[ng-init]
. For example, if you click on the year '2012' in either section, it changes the year
property in both sections.
Is there a way to tell angular to create a new scope for each ng-init and thereby clicking the '2012' year will only impact the section that it belongs to?
ng-init
does not create a new scope, it evaluates an expression in the current scope. In your example, both your ng-init
are in the same scope, changing the same model property will affect the other. If you need separate scope, you could try ng-controller
.
<div ng-controller="MainCtrl" ng-init="model = { year: '2013'}">
<a href="" ng-click="model.year = '2012'">2012</a> | <a href="" ng-click="model.year = '2013'">2013</a>
<div>Showing {{ model.year }}</div>
<hr />
</div>
<div ng-controller="MainCtrl" ng-init="model = { year: '2013'}">
<a href="" ng-click="model.year = '2012'">2012</a> | <a href="" ng-click="model.year = '2013'">2013</a>
<div>Showing {{ model.year }}</div>
</div>
DEMO
Side notes: In this case, you don't need ngInit, just initialize the value directly in your controller.
The only appropriate use of ngInit is for aliasing special properties of ngRepeat. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
https://docs.angularjs.org/api/ng/directive/ngInit
Since ng-if
creates a new scope, you can accomplish it just by:
<div ng-if="true" ng-init="model = { year: '2013'}">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With