gpt4 book ai didi

javascript - 当使用angularjs,ngInit加载 View 时初始化范围值的正确方法?

转载 作者:数据小太阳 更新时间:2023-10-29 06:06:54 24 4
gpt4 key购买 nike

在过去的几周里,我一直在学习 angularJs,并一直在研究许多大型应用程序,以了解其在现实世界中的运作方式。在大多数情况下,我注意到加载 View 时:

ng-init="init()"

即在相关 Controller 中调用函数 init()。用于设置初始值。

但是(很大但是)在阅读 ngInit 上的 Angular 文档时,我得出了一个相当严厉的描述:

"The only appropriate use of ngInit 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."

所以我的问题是,加载 View 时使用 ngInit 初始化范围内的值是不好的做法吗?如果是这样,这是为什么?什么是正确的方法?

最佳答案

这是一种不好的做法,因为 View 的初始化时间与 Controller 的初始化时间不同,并且摘要循环必须处理该函数,这是对该循环不必要的补充。我假设你有类似的东西:

查看:

<div ng-init="init()">
<span>{{thing}}</span>
</div>

Controller :

Module.controller('viewController', function(scope){
...
var init = function(){
scope.thing = "123";
...
}
...
})

更好的做法是这样做:

查看:

<div>
<span ng-bind="thing"></span>
</div>

Controller :

Module.controller('viewController', function(scope){
scope.thing = "123";
})

关于javascript - 当使用angularjs,ngInit加载 View 时初始化范围值的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com