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

倖福魔咒の 提交于 2019-12-30 09:38:17

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/20546819/correct-way-to-initialise-scope-values-when-the-view-is-loaded-with-angularjs-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!