Using jQuery's $.ajax within an angularJS controller

13,837

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.

Share:
13,837
Dynalon
Author by

Dynalon

Updated on June 04, 2022

Comments

  • Dynalon
    Dynalon about 2 years

    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?