在角度js ng-repeat之后重新绑定jquery

Cha*_*dig 3 javascript jquery binding angularjs angularjs-ng-repeat

我正在使用$http.get()服务填充angularJS中的数组,通过调用rest api.使用此数组显示此数组ng-repeat.有一个Jquery代码可以在每个<li>标记上方悬停时显示一个按钮.$http导致数据获取延迟,此时Jquery将完成绑定.所以悬停功能不起作用.有没有解决这个问题?

<!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>
Run Code Online (Sandbox Code Playgroud)

pko*_*rce 17

虽然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>
Run Code Online (Sandbox Code Playgroud)

请注意,这就是使其工作所需的全部内容:无需对DOM元素进行adid,也无需编写任何 JavaScript代码.它允许我们删除14行JavaScript代码并完全删除对jQuery的依赖.甜,不是吗?

最后这是一个有效的jsFiddle:http://jsfiddle.net/GBwLN/4/

  • 虽然这个答案并不完全是chai.nadig所寻求的,但应该注意未来的用户通过Google等发现这个问题,这是在Angular中这样做的正确方法. (4认同)

Nel*_*son 6

使用事件委托,这是新.on()jQuery方法引入的更好的方法,只需替换以下代码:

$("#orders ul li").hover(
        function() {
            $(this ).find(".butt-view").show();
        },
        function() {
            $(this ).find(".butt-view").hide();
        });
Run Code Online (Sandbox Code Playgroud)

对于这一个:

$("#orders").on('mouseenter mouseleave', 'li', function(event) {
     if (event.type == 'mouseenter') {
         $(this ).find(".butt-view").show();
     } else  {
         $(this ).find(".butt-view").hide();
     }
});
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以将事件处理程序附加到#ordersdiv而不是单个li元素,当li元素悬停时,事件将冒泡直到到达处理程序#orders.这种方法更有效,并且可用于dinamycally添加新的li.

顺便说一下,我使用 mouseenter mouseleave的东西相当于hover并且在我看来更具可读性.