Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery's $.ajax within an angularJS controller

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?

like image 315
Dynalon Avatar asked Feb 05 '13 21:02

Dynalon


People also ask

Can we use AJAX in Angular JS?

The AngularJS provides a control service named as AJAX – $http, which serves the task for reading all the data that is available on the remote servers. The demand for the requirement of desired records gets met when the server makes the database call by using the browser. The data is mostly needed in JSON format.

Can we use AJAX in JavaScript?

AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)

Can you use jQuery with AJAX?

What About jQuery and AJAX? jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

What is AJAX method in JavaScript?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.


1 Answers

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.

like image 84
Shai Reznik - HiRez.io Avatar answered Sep 19 '22 01:09

Shai Reznik - HiRez.io