I'm trying to use AngularJS within an POST request, but I cannot use $scope within the event.
Thats my code (for demonstration purpose I just add status within the Angular construct):
myApp.controller('myController', function myController($scope) {
$scope.myVal = [{status:"before (working)"}];
doRequest(p1, p2, myCallback.bind(null, $scope));
function myCallback($scope, a) {
$scope.myVal = [{ status: a }];
}
function doRequest(p1, p2, callback) {
$scope.myVal = [{ status: "prepare request (working)" }];
var xhr = new XMLHttpRequest();
var url = "http://...";
xhr.open("POST", url, true);
//....
xhr.send(myQuery);
$scope.myVal = [{ status: "after post send (working)" }];
callback("after post via callback (working)");
//callback working till this point
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
callback("in event (NOT working)");
//This is NOT working anymore (even this point is reached)!
}
};
}
as added via comments in the code, the callback is working till the EventHandler assignment.
What I'm looking for is: How to use the callback (or more precise how to make $scope available/transfered in the event handler function)?
$httpto make the request. You are trying to modify the scope in asynchronous code that is outside of angular context. When you do that angular needs to be told to run a digest to update the view. Using$httptakes care of that internally