Reputation: 447
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.
Upvotes: 3
Views: 799
Reputation: 9560
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.
Upvotes: 0
Reputation: 2777
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.
Upvotes: 0
Reputation: 1231
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'
};
});
Upvotes: 2