When an angularjs site initially starts up, it can take a little time for all the various HTTP requests to complete.
HTTP requests
- GET Index.cshtml
- GET the various JS and CSS files (hopefully only one minified version of each) Now angularjs starts up. Usually the first thing an angular controller will do it to get data for the UI:
1 2 3 4 5 6 7 |
|
This is yet another HTTP request. However it is one that we do not have to make if we make use of ng-init
.
Create the ViewModel/DataModel:
1 2 3 4 5 |
|
In the MVC controller:
1 2 3 4 5 6 7 8 9 10 |
|
In the html:
1 2 |
|
Our angularjs controller changes to:
1 2 3 |
|
And now we have the user
object in our controller $scope
.
Just be aware that the ng-init is on the same HTML element as the ng-controller so it will run after the controller is instantiated. The object will get put on the controller $scope
but will be available immediately in the controller init path. You can use the $scope.evalAsync
function in that case which will re-evaluate the $scope.user on the $digest cycle.