我正在使用 $http.get()
在 angularJS 中填充一个数组服务,通过调用 rest api。该数组使用 ng-repeat
显示.有 Jquery 代码显示悬停在每个 <li>
上的按钮。标签。 $http
导致获取数据的延迟,到那时 Jquery 将完成绑定(bind)。所以悬停功能不起作用。有什么解决方法吗?
<!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>
最佳答案
虽然 jQuery 方法可能工作正常,但这并不是真正解决问题的 AngularJS 方法。
AngularJS 提倡以声明方式表达 UI(换句话说,我们确实描述了想要的效果,而不是指示为实现效果而采取的每一个小步骤)。 使用指令,我们可以告诉 AngularJS 我们希望我们的 UI 看起来如何以响应模型突变。因此,对于 AngularJS,我们更专注于在模板中以声明方式描述 UI,然后通过模型突变驱动此 UI。 AngularJS 将完成剩下的繁重工作。
这一切听起来可能有点神秘,所以这里是用 AngularJS 方式解决的问题(模型不会改变,只有模板会改变):
<ul>
<li ng-repeat="phone in phones" ng-mouseenter="showView=true" ng-mouseleave="showView=false">
{{phone.name}}
<p>{{phone.snippet}}</p>
<p class="butt-view" ng-show="showView">View</p>
</li>
</ul>
请注意,这就是让它工作所需的全部:无需将 id 添加到 DOM 元素,也无需编写任何 JavaScript 代码。 它允许我们删除 14 行 JavaScript 代码并完全删除对 jQuery 的依赖。很甜蜜,不是吗?
最后这是一个可以工作的 jsFiddle:http://jsfiddle.net/GBwLN/4/
关于javascript - 在angular js ng-repeat之后重新绑定(bind)jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13543829/