【问题标题】:try to change ng-class with ng-mouseover and ng-mouseleave尝试使用 ng-mouseover 和 ng-mouseleave 更改 ng-class
【发布时间】:2017-07-11 16:54:30
【问题描述】:

我有这个代码:

控制器:

var ratingTotal = 5;
$scope.count = 0;
$scope.getRepeater = function() {
       return new Array(ratingTotal);
};

HTML:

<div>
    <span ng-repeat="r in getRepeater() track by $index" ng-mouseover="count = count + 1" ng-mouseleave="count =count-1" ng-class="{'icon-star-full': ($index + 1) <= count, 'icon-star-empty': ($index + 1) >= count}"></span>
</div>

我试图通过将鼠标移到图标上来使图标开始完整显示,并在离开 div 时消失,但它不起作用

PD:icon-start-full 和 icon-start-empty 类是 icomoon 类

【问题讨论】:

  • 这对您有帮助吗? using mouseover in angular
  • 为什么不在鼠标悬停时将 count 设置为 $index(或 $index + 1,如果您的评分为 1-5 而不是 0-4)?
  • @mhodges 如果我删除 mouseleave,它会像你说的那样工作,但我也想要 mouseleave
  • @DavidAlzate88 看看我的回答

标签: javascript angularjs html


【解决方案1】:

通过使用此代码几分钟可以明显看出ng-mouseoverng-mouseleaveng-class 中引用的count 变量不是同一个变量。 Angular 有时会使用像这样的变量作用域来做一些时髦的事情,所以这是一个完美的例子,说明为什么你应该总是在 AngularJS 中使用controller as 语法。关于如何以及为什么使用它,Here, by Todd Motto 有据可查。

您可以通过以下方式修改代码以使其与 controller as 一起使用,这样您就不会遇到您遇到的范围界定问题。

var app = angular.module("myApp", [])
.controller("myCtrl", function (){
  var $this = this;
  var ratingTotal = 5;
  $this.count = 0;
  $this.getRepeater = function() {
    return new Array(ratingTotal);
  };
});
.icon-star-full, .icon-star-empty {
  padding: 10px;
}
.icon-star-full {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl as Main">
  <div>
    <span ng-repeat="r in Main.getRepeater() track by $index" ng-mouseover="Main.count = $index + 1" ng-mouseleave="Main.count = 0" ng-class="{'icon-star-full': ($index + 1) <= Main.count, 'icon-star-empty': ($index + 1) >= Main.count}">{{$index + 1}}</span>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    相关资源
    最近更新 更多