简体   繁体   English

使用angularjs,ngInit加载视图时,初始化范围值的正确方法是什么?

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

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. 过去几周我一直在学习angularJs,并且正在研究一些大型应用程序,以了解现实世界中的工作原理。 In most of them I have noticed when a view is loaded : 在大多数情况下,我注意到加载视图时:

ng-init="init()"

ie the function init() is called in the relevant controller. 即在相关控制器中调用函数init()。 Is used to set the initial values. 用于设置初始值。

BUT(big but) when reading through the angular docs on ngInit i came to a rather stern looking description: 但是(很大但是)在阅读ngInit上的角度文档时,我得到了一个相当严厉的描述:

"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? 所以我的问题是,在加载视图时使用ngInit初始化作用域中的值是不好的做法? if so , why is this ? 如果是这样,为什么会这样? and what is the correct way? 什么是正确的方法?

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";
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM