What's the best way to run jquery code in angularjs?

I want to run some jquery code when DOM Ready. I used

angular.element(document).ready(function() {
$(".hover-brown").mouseover(function(e) {
        if ($(e.target).closest('.hover-yellow').length == 0) {
          $(this).not(".hover-yellow").css("background", "#e8e8e8");
      }).mouseout(function() {
        $(this).not(".hover-yellow").css("background", "white");

    $(".hover-yellow").hover(function() {
      $(this).css("background", "#e8e8e8");
    }, function() {
      $(this).css("background", "white");


and tried it window.load

, but it starts before Dom is ready since it doesn't find items when doing this function.

Note. Elements are <li>

hover-brown rendered elements using the ng-repeat directive.


source to share

3 answers

You've made some conceptual mistakes. When using angular js you should avoid the "jquery template" for DOM event assignment. Instead, you should use the directive directly on the DOM element.

For example, if you need the browser to run some custom code on hover, you must create a function in your controller and assign the element via the ngMouseover directive ( https://docs.angularjs.org/api/ng/directive/ngMouseover ).

The same approach will be used to change the style of your nodes. You have to use some variables that represent states (like active) and bind the css definition to those variables.

You can take a look here: http://codepen.io/anon/pen/gpBEgR

angular.module('demo',  []).controller('MyController', function($scope) {
  $scope.over = function() {
    $scope.style['backgroundColor'] = 'yellow';
  $scope.out = function() {
    $scope.style['backgroundColor'] = 'green';
  $scope.style = { 
    backgroundColor: 'green'




There is no problem using jquery in angularjs, but you should use it in context, for example if it involves using the page in a controller. If it has to do with a directive, use it in directive references or controller functions. This way, you can be sure that the document is loaded.




not installed until bindJQuery()

in Angular (Angular 1.4.1, line 28288):

jqLite(document).ready(function() {
    angularInit(document, bootstrap);


So it is angular.element

not available until the document is ready.

You should prevent a way to jQuery

manipulate DOM structures. If you want to do this, move the operation to a link

function directive
. This means move the code $(".hover-brown").mouseover(function(e) {...

to some directive link




All Articles