0

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 ?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah but then If I want to initialize a function on a specific view but not the other I need to do more than just that which ng-init provides without any further work.
0

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.

1 Comment

then could you suggest what's the best practice to call data on page loading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.