来自 the ng-init documentation :
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
该文档继续给出以下示例:
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
// [snip]
</div>
什么使使用更合适
ng-init
与 ng-repeat
但不是,例如,使用 ng-model
像这样:<input ng-model="thing.prop"
ng-init="thing.prop = thing.prop || 'defaultValue'">
该文档说应该“使用 Controller 而不是 ngInit”。在这种情况下, Controller 有什么好处?这是 Angular 的风格偏好,还是在某些情况下上述代码不起作用?
最佳答案
那是因为文档要尽量简洁,如果在每个例子中都创建了一个Controller,就不会那么精确和清晰
关于javascript - 为什么 Angular 文档在大多数情况下建议不要使用 ng-init?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418637/