10

How can I use jQuery's $.ajax() function inside an angularJS controller (instead of angularJS built-in $http) so that the $scope values can be accessed from a view/template later?

I have this somewhat minimalistic angularJS controller:

function UserCtrl($scope, $http) {
    $.ajax('http://localhost:8080/admin/user/johndoe').success(function(data) {
        $scope.user = data;
    });
}

And in the view something like:

<h1>Hello, {{ user.Username }}</h1>

However, the <h1> in the view will be empty on load, altough a console.log() in the controller tells me that $scope.user is populated just as I want.

Now, If I replace the $.ajax() call with $http.get() everything works fine as expected.

I know of $http that is angularJS built-in, but since I am not starting from scratch but have already lots of code that uses jQuery throughout, I want to stick to jQuery for $.ajax().

Any ideas?

1 Answer 1

23

Because using jQuery ajax is out of the world of angular, you need to wrap your $scope assignment inside of

$scope.$apply(function(){
    $scope.user = data;
});

Angular's $http comes pre-built with the digest cycle triggering mechanism.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.