2017-02-21 59 views
2

我有這樣的代碼:嘗試改變NG-類NG-鼠標懸停和NG-鼠標離開

控制器:

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:class icon-start-全和圖標啓動空是icomoon類

+0

這是否幫助你嗎? [使用鼠標懸停在角度](http://stackoverflow.com/questions/22532656/ng-mouseover-and-leave-to-toggle-item-using-mouse-in-angularjs) – Soorena

+0

爲什麼不只是設置計數等於$在鼠標懸停的情況下索引(或者'$ index + 1',如果你的評分爲1-5而不是0-4)? – mhodges

+0

@mhodges它如你所說,如果我刪除mouseleave,但我也想mouseleave – DavidAlzate88

回答

3

正是從這段代碼玩弄幾分鐘的count變量在ng-mouseoverng-mouseleave引用明顯,ng-class是不一樣的變量。 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>

+0

感謝兄弟你真棒! – DavidAlzate88

+0

@ DavidAlzate88不客氣!很高興我能幫忙=) – mhodges