Reputation: 23214
I'm trying to replace Knockout with Angular right now. However, there seems to be some quirks that I simply can not get around so far.
In the login function of my site, I do an ajax call and get some user information, this info is then set in the controller.
like this:
$scope.login = function () {
var data = {
userName: $('#txtLoginName').val(),
password: $('#txtLoginPassword').val(),
};
console.info(data);
postJSON("/StrengthTracker/User/Login", data, function (result) {
if (result.result == "ok") {
$('#loginDialog').modal('hide');
//setting controller variables <------------
$scope.isLoggedIn = true;
$scope.userId = result.userId;
$scope.userName = result.userName;
$scope.publicId = result.publicId;
$scope.gender = result.gender;
$scope.unitName = result.unit;
console.info(result);
notify("Welcome " + $scope.userName);
}
if (result.result == "fail") {
notifyFail("Login failed");
}
});
}
I can see that the correct data is returned, the notify(..) call does say "Welcome Roger" for example. so far so good. But it seems like Angular doesnt see that the variables have changed.
If I do hit the login function again, THEN angular notices the changes and understands that the user is logged in.
Ideas?
Upvotes: 0
Views: 85
Reputation: 5745
This has to do with AngularJS not being aware of your callback function, it's not tracked. As Yoshi already suggested, using $scope.$apply
fixes it because this forces AngularJS to become aware.
Note that AngularJS has built-in support for making AJAX-requests with $http
and $resource
(in case of REST services). One of the advantages of using one of these objects is that you won't have to manually use $apply
, another is that your code remains testable with the built-in support for unittests.
Upvotes: 1