Hi
I’ve been using the following script to create update-able content:
function loadXMLDoc()
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.example.com/example.txt",true);
xmlhttp.send();
}
Then i have created a button in the specific template like this:
<a class="item" onclick="loadXMLDoc()">
example
</a>
<div id="myDiv"></div>
All of this works just fine, but now i want it to load the script when i enter the page instead of the user having to press a button. How would i best do that?
Probably the best way is to use a resolve
, I’m using them extensively with ui-router in order to resolve HTTP requests.
It works best when you have a controller that loads for the respective page the user is navigating to.
In my router:
$stateProvider.state('app.new_survey', {
url: '/surveys/new',
views: {
menuContent: {
templateUrl: 'templates/surveys/main.html',
controller: 'SurveyCtrl',
resolve: {
survey: function(Survey, $q) {
var defer;
defer = $q.defer();
Survey.query(function(response) {
return defer.resolve(response);
});
return defer.promise;
}
}
}
}
});
Should note that Survey
is an ngResource.
And, inside the SurveyCtrl
, I require the survey
object I’m resolving as a dependency:
angular.controller("SurveyCtrl", function($scope, $state, survey)
This way, whenever SurveyCtrl is instantiated, the resource is ready.
For more information, read this post: http://blog.brunoscopelliti.com/show-route-only-after-all-promises-are-resolved