无法在角度js鼠标悬停事件中访问我的选择器

时间:2013-08-01 09:34:14

标签: angularjs angularjs-directive angularjs-scope

我无法访问div中的li元素。我将mouseover事件添加到li,但它仅绑定到其父div。

HTML:

<div>
    <ul class="rating">
           <li ng-repeat="star in stars" ng-class="star" ng-click="toggle($index)"       
              ng-mouseover="starHover($index)" id="$index"> \u2605'
           </li>
    </ul>
</div>

JS指令链接鼠标悬停功能:

scope.starHover = function(index) 
{
     elem.addClass('unfill').removeClass('filled');
}

我想访问我鼠标悬停的li和nextAll li也是。

2 个答案:

答案 0 :(得分:4)

不要在范围内进行,在指令中执行。像这样更改您的li标记:

 <li ng-repeat="star in stars" ng-class="star" ng-click="toggle($index)" id="$index" mousable >  <!-- ... -->  </li>

并创建mousable这样的指令:

 yourApp.directive('mousable', function () {    
     return {       
         link: function(scope, element, attrs , ctrl) {
               element.bind("mouseover", function(e){    
                     element.addClass('unfill').removeClass('filled');
               });
               element.bind("mouseout", function(e){
                     element.addClass('filled').removeClass('unfill');
               });    
          }
      }
  }

参考文献:
http://docs.angularjs.org/api/angular.element
http://docs.angularjs.org/guide/directive

答案 1 :(得分:1)

以角度方式做到:

<div>
    <ul class="rating">
           <li ng-repeat="star in stars" ng-class="{star: true, unfill: hovered, filled: !hovered}" ng-click="toggle($index)"       
              ng-mouseenter="hovered = true" ng-mouseleave="hovered = false" id="$index"> \u2605'
           </li>
    </ul>
</div>

http://jsfiddle.net/AVCT4/