[英]initialize a scope variable with angularJs
I'm always using ng-init="controllerFunction()"
to get data from the server and display it on a table, chart or anything else and it needs to get called on every page loading. 我一直在使用
ng-init="controllerFunction()"
从服务器获取数据并将其显示在表,图表或其他任何东西上,并且每次加载页面时都需要调用它。
Now using ng-init
is doing the job but is it the best practice ? 现在使用
ng-init
做这项工作,但这是最佳实践吗?
ng-init
is mainly used to pass data to an init method, for example razor data ( ng-init="someControllerFunction(@Model.ServerSideData)
). If you don't pass any data you can just do it directly in your controller: ng-init
主要用于将数据传递给init方法,例如剃刀数据( ng-init="someControllerFunction(@Model.ServerSideData)
)。如果您不传递任何数据,则可以直接在控制器中进行操作:
function myCtrl($scope) {
function myInitFunction(){
// fetch data etc.
}
myInitFunction();
}
This way you don't expose the init function and is nicely encapsulated inside your controller. 这样,您就不会公开init函数,并且很好地封装在控制器中。
The documentation clearly states (in a big red alert) that ngInit
has only a few focused use-cases, and should not be used outside of these scenarios 该文档明确指出(在红色警告中)
ngInit
仅具有一些针对性的用例,并且不应在这些情况下使用
This directive can be abused to add unnecessary amounts of logic into your templates.
可以滥用此指令在模板中添加不必要的逻辑量。 There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below;
ngInit只有少数适当的用法,例如别名ngRepeat的特殊属性,如下面的演示所示; and for injecting data via server side scripting.
以及通过服务器端脚本注入数据。 Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.
除了这几种情况,您应该使用控制器而不是ngInit来初始化作用域上的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.