javascript 当视图加载 angularjs、ngInit 时初始化范围值的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20546819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:45:41  来源:igfitidea点击:

correct way to initialise scope values when the view is loaded with angularjs, ngInit?

javascriptangularjsviewangularjs-scopeangularjs-ng-init

提问by Aidan Gee

I've been learning angularJs for the past few weeks and been looking at a number of large scale apps to see how things work in the real world. In most of them I have noticed when a view is loaded :

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

ng-init="init()"

i.e. the function init() is called in the relevant controller. Is used to set the initial values.

即函数 init() 在相​​关控制器中被调用。用于设置初始值。

BUT(big but) when reading through the angular docs on ngInit i came to a rather stern looking description:

但是(大但是)在阅读 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."

“唯一合适使用 ngInit 为 ngRepeat 的特殊属性设置别名,如下面的演示所示。除此之外,您应该使用控制器而不是 ngInit 来初始化范围上的值。”

so my question is, Is it bad practise to use ngInit to initialise the values in a scope when the view is loaded? if so , why is this ? and what is the correct way?

所以我的问题是,在加载视图时使用 ngInit 初始化作用域中的值是不好的做法吗?如果是这样,这是为什么?正确的方法是什么?

回答by Fourth

It is bad practice because the view is initialized at a different time than the controller AND the digest cycle has to process that function, which is an unnecessary addition to that cycle. I assume you have something like:

这是不好的做法,因为视图在与控制器不同的时间初始化,并且摘要循环必须处理该函数,这是对该循环的不必要添加。我假设你有这样的事情:

View:

看法:

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

Controller:

控制器:

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

The better practice is to do this:

更好的做法是这样做:

View:

看法:

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

Controller:

控制器:

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