当视图装有angularjs初始化值范围正确的方法,ngInit? [英] correct way to initialise scope values when the view is loaded with angularjs, ngInit?

查看:269
本文介绍了当视图装有angularjs初始化值范围正确的方法,ngInit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习过去几周angularJs,并一直在寻找一些大型的应用程序看到的事情在现实世界中是如何工作的。在大多数人当一个视图被加载,我注意到:

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 :

ng-init="init()"

即。功能的init()被调用的相关负责人。用于设置初始值。

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

但通过对ngInit角文档我来到了一个相当严峻的描述看阅读时(但大):

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

唯一的适当使用ngInit的混叠ngRepeat的特殊属性,如下面的演示看到,除了这种情况下,你应该使用控制器,而不是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视图加载时初始化一个范围值?
如果是这样,这是为什么?什么是正确的方法是什么?

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?

推荐答案

这是不好的做法,因为该视图是在不同的时间控制器和消化周期进行初始化已处理的功能,这是一种不必要的除了周期。我假设你有这样的:

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:

查看:

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

控制器:

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

更好的做法是这样:

The better practice is to do this:

查看:

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

控制器:

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

这篇关于当视图装有angularjs初始化值范围正确的方法,ngInit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆