Is it possible to fetch data before calling the controller and loading the HTML file using resolve?
Absolutely. One way to achieve this is by using resolve to preload the dataset you wish to display on your view prior to initializing the corresponding controller.
There are a few methods that come to mind;
- Using ui-router#resolve.
- Utilizing ngRoute#resolve.
- Deferring the compilation of the DOM linked to your controller.
ui-router#resolve
// define state
.state('myState', function () {
resolve: {
dataset: function (Service) {
return Service.getData();
}
},
controller: 'Controller'
})
// define controller
.controller('Controller', function (dataset) {
this.dataset = dataset;
})
The resolved data will be accessible in the defined controller of the state (either through the state definition itself, or via a ng-controller
at the top level of your state template).
ngRoute#resolve
// define route
.when('/path', {
resolve: {
dataset: function (Service) {
return Service.getData();
}
},
controller: 'Controller'
})
// define controller
.controller('Controller', function (dataset) {
this.dataset = dataset;
})
This essentially follows the same approach as shown in the ui-router example.
ngIf
Postponing the rendering of your template until the promise resolves.
.controller('outer', function ($timeout) {
this.resolved = false;
this.dataset = [];
$timeout(function () {
this.resolved = true;
this.dataset = [ {}, {} ];
}.bind(this), 1500);
})
.controller('inner', function () {
console.log('I just executed!');
})
<div ng-controller="outer as o">
<div ng-controller="inner as i" ng-if="o.resolved">
{{o.dataset}}
</div>
</div>
Check out the solution on jsfiddle