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.
Now using ng-init
is doing the job but is it the best practice ?
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:
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.
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
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; 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.