I’m filling in an array in angularJS using $http.get() service, by calling a rest api. This array is displayed using ng-repeat. There is Jquery code to display a button on hovering over each of the <li> tags. $http causes a delay in fetching the data, by which time Jquery would have finished binding. So the hover function doesn’t work. Any work arounds for this?
<!doctype html>
<html ng-app>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="angular.js"></script>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
myFunction();
});
var myFunction= function(){
$("#orders ul li").hover(
function() {
$(this ).find(".butt-view").show();
},
function() {
$(this ).find(".butt-view").hide();
});
}
</script>
<script>
function PhoneListCtrl($scope) {
$scope.phones = $http.get(url);
}
</script>
<style>
ul{list-style-type:none;}
ul li{background-color:#e1eff2; padding:5px 6px;}
ul li:hover{background-color:#fff;}
.butt-view{background-color:#feb801; border-radius:4px; color:#fff; font: bold 12px Arial, Helvetica, Sans-serif; padding:5px 7px; margin-top:3px; width:40px }
</style>
</head>
<body ng-controller="PhoneListCtrl">
<div id="orders">
<ul>
<li ng-repeat="phone in phones" >
{{phone.name}}
<p>{{phone.snippet}}</p>
<p class="butt-view">View</p>
</li>
</ul>
</div>
</body>
</html>
Use event delegation, which is better approach introduced by the new
.on()jQuery method, to do it just replace your following code:for this one:
This way you will attach your event handler to your
#ordersdiv, instead of the individuallielements, when alielement is hovered the event will bubble up till gets to your handler on#orders. This approach is more eficient and will work for dinamycally added new li’s.By the way I’m using
mouseenter mouseleaveevents which are equivalent tohoverand are more readable in my opinion.