3

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 window.load as well but it runs before Dom is ready i.e it does not find the elements when this function run.

Note: the elements are the <li>elements with class hover-brown rendered in view using ng-repeat directive.

3 Answers 3

2

You did some conceptual errors. When you're using angular js you should avoid "jquery pattern" to assign event to the DOM. You shouldi instead use directive directly on DOM element.

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

The same approach would be used for alter style of your nodes. You should use some variables that represents states (for example active) and bind css definition to this 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'
  };
});   
Sign up to request clarification or add additional context in comments.

Comments

0

There is no problem with using jquery in angularjs, but you should use it within the context, like if it's related to a page use it in the controller. If it's related to a directive use it in directive's link or controller functions. That way, you will be sure that the document is loaded.

Comments

0

angular.element is not set until bindJQuery() in Angular is executed (Angular 1.4.1, Line 28288):

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

So angular.element is not availabe before document is ready.

You should prevent the jQuery way to manipulate DOM structures. If you do want to do it, move the operation to the directive link functions. That means, move your code $(".hover-brown").mouseover(function(e) {... to some directive link function.

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.