尝试使用 ng-mouseover 和 ng-mouseleave 更改 ng-class



我有这个代码:

控制器:

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:类图标开始满和图标开始空是 icomoon 类

通过玩弄这段代码几分钟可以明显看出,ng-mouseoverng-mouseleaveng-class中引用的count变量不是同一个变量。Angular 有时会像这样使用变量作用域做一些时髦的事情,所以这是一个完美的例子,说明为什么你应该始终在 AngularJS 中使用controller as语法。托德·莫托(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>

最新更新