So, I want to get data from an API (provided by Laravel). I am using $http in Angular to get this data, and when I send it forward to my view, it works fine, but when I want to use the data inside the controller, it doesn't:
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/js/MainController.js"></script>
</head>
<body ng-controller="MainController as myControl">
<h1>Todo-list:</h1>
<div>
<table>
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
</tr>
<tr ng-repeat="todo in myControl.todos">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button ng-click="myControl.showUpd(todo.id)">Update</button></td>
</tr>
</table>
</div>
</body>
</html>
Angular Controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
// Below works without any problems when accessing it from the html-view:
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
// But this function doen't work as intended
thisApp.showUpd = function(noteID) {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
thisApp.getNote = response.data;
console.log(thisApp.getNote); // MainController.js:20
alert("Got data");
}, function() {
alert("Error getting todo note");
});
console.log(thisApp.getNote); // MainController.js:26
}
});
The console gives me the following:
MainController.js:26 undefinedMainController.js:20 Object {id: 1, content: "asdasd", completed: 0, deadline: "2016-01-14 10:29:38"}
My problem is that when I access thisApp.getNote inside the $http it works fine, but when I try to access it outside I only get undefined. I have tried changing thisApp to $scopeandd I have also tried to declare another var inside the function, none of them made any difference.
Can anyone spot my problem?
thisApp.getNotehasn't been set yet, so it is undefined. It is available "outside" the $http, but only after it is set, which doesn't happen until the $http call is resolved, which happens sometime in the future (if at all).