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

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

问题描述

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

ng-init="init()"

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

BUT(big but) 在阅读 ngInit 上的 angular 文档时,我看到了一个相当严厉的描述:

<块引用>

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

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

解决方案

这是不好的做法,因为视图是在与控制器不同的时间初始化的,并且摘要循环必须处理该函数,这是不必要的补充循环.我假设你有类似的东西:

查看:

<span>{{thing}}</span>

控制器:

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

更好的做法是这样做:

查看:

<span ng-bind="东西"></span>

控制器:

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

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()"

i.e. the function init() is called in the relevant controller. 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:

"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."

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:

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

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

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