Angular中的ng-init的范围是什么?以下是一个简单的例子来说明我的问题:
<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>
现场示例:http://plnkr.co/edit/HkioewOzzglvFMKDPdIf?p=preview
似乎ng-init范围在2 div [ng-init]之间共享.例如,如果您点击年份“2012”,它会更改两个部分.有没有办法告诉角度为每个ng-init创建一个新的范围,从而点击“2012”年只会影响它所属的部分?
ng-init不会创建一个新的作用域,它会计算当前作用域中的一个表达式.在您的示例中,您的ng-init都在相同的范围内,更改相同的模型属性将影响另一个.如果您需要单独的范围,您可以尝试ng控制器.
<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>
旁注:在这种情况下,您不需要ngInit,只需直接在控制器中初始化该值.
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.