Before using jQuery, ensure it’s included in your project before AngularJS.
Using CDN (Recommended)
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
By default, AngularJS uses its own lightweight jQuery-like library called jqLite. To make sure AngularJS uses full jQuery, it must be loaded before AngularJS.
Inside your AngularJS app:
console.log(angular.element === jQuery);
You can use jQuery inside AngularJS controllers, directives, and services.
However, always use AngularJS lifecycle methods like $timeout or $apply when modifying the DOM.
Example 1: Using jQuery in a Controller
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope, $timeout) {
$scope.changeText = function () {
$timeout(function () {
$("#myText").text("Updated by jQuery!");
}, 0);
};
});
html
Original Text
Example 2: Using jQuery in a Directive
app.directive("customDirective", function () {
return {
restrict: "A",
link: function (scope, element, attrs) {
$(element).on("click", function () {
$(this).css("background-color", "yellow");
});
}
};
});
html
button custom-directive>Click Me
Do not directly manipulate the DOM inside controllers. Use directives instead.
Use AngularJS lifecycle methods ($timeout, $apply) to avoid issues with two-way data binding.
Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular Developers