Jan Kowalski Jan Kowalski - 2 months ago 22
AngularJS Question

ngStorage ($localStorage) dosen't work in .then()

I have problem with ngStorage. When I use my factory for jQuery's

$ajax
, I can't use
$localStorage
in
.then()
(it dosen't work).

$scope.updateProfile = function () {
updateProfileFactory.init($scope.dataProfile).then(
function (data)
if (data.status == "success") {
$localStorage.currentUser.fullname = $scope.dataProfile.u_fullname;
}
}
)
}


If I use
$localStorage
outside
.then()
, it work's fine, but I must put it inside.

$scope.updateProfile = function () {
$localStorage.currentUser.fullname = $scope.dataProfile.u_fullname;
updateProfileFactory.init($scope.dataProfile).then(
function (data) {
if (data.status == "success") {
// code
}
}
)
}


Where is the problem?

Answer

Why don't you use Angular's $http library to do your AJAX stuff? Mixing jQuery and Angular proves to give unpredictable results.

I can see that you already use Angular in your application. So there really is no reason why you shouldn't go the Angular way completely. The $http service provides all of the functionality that jQuery's $.ajax provides and more.

When you use Angular functions within vanilla Javascript or jQuery functions, Angular doesn't know that these are called, as they are outside it's scope. Here you can possible use Angular's $apply, but that is not ideal and is hacky.

Here your problem might be that the callback function of your $.ajax is not aware of $localStorage as it is not passed in as a dependency.