I have been trying to get my angular application to make an ajax request as soon as my page is done loading based on the content of a pre-filled hidden field. However, my attemps so far have been rather futile as most methods I've seen so far of running a method on page load don't necessarely wait for fields to be populated. In the following sample code, if(!isNaN(id))
always fails because $scope.item_id
is still empty by the time the method is called no matter how I run it, which means parseInt()
returns undefined
.
<input type="hidden" ng-model="item_id" value="1">
<input ng-model="item_data">
$scope.loadItem = function(){
var id = parseInt($scope.item_id)
if(!isNaN(id)){
$http.get('/items/get/' + id).success(function(data) {
$scope.item_data = data;
});
}
}
How am I supposed to get this method to run after the fields have been initialized, or is there a way to initialise them so that angular will be able to see them before sending the ajax request?
For those wondering, I'm doing this because I need my script to be static and I can only generate the html code on the page, but I'm loading a json array that will be handeled by the script to display a list of objects, meaning I kind of need to fetch it via json. There might be an easier way to do this, but I haven't thought of one so far.
EDIT: Someone proposed that question #14968690 might awnser mine, however my problem is not so much that I can't make an ajax request happen as soon as angular is loading, but that I can't make sure that the data I pass to my view via an hidden input field is already avilable.
EDIT2 (Solution): After tring to get some of the proposed solutions to work, I tried putting my controller script at the end of my body rather than at the beginning and declaring my variable directly in the scope rather than in a field that may or may not be initialized by the time the js runs (and bind an ng-model on this field with that variable if I want to put it in a form) like so:
<script>menu_id=1</script>
<script src="/static/scripts/app.js"></script>
<input type="hidden" name="menuId" ng-model="menu_id">
While that does not anwser the exact question I first asked, it does solve the issue that let me to ask that question.