这个笨蛋有几个问题。
首先,这里没有理由使用 ng-model。只需将其设置为范围变量即可,因为无论如何您都在从控制器中对其进行编辑。
其次,mousemove 会连续执行。每次移动鼠标时,它都会创建一个新的超时,并且不会取消旧的超时。这就是它闪烁的原因。调用这个函数并不断调用$timeout.cancel()和$timeout(function() { }, 3000)也是非常低效的。
请考虑使用 mouseenter 和 mouseleave 并确保取消旧的超时。
HTML
<div ng-app="myApp" ng-controller="myController">
<div class="mousemove" ng-mouseenter="enter()" ng-mouseleave="leave()"></div>
<div class="show" ng-show="loading"></div>
</div>
Javascript
var myApp = angular.module('myApp',[]);
myApp.controller('myController', function($scope, $timeout) {
var timeoutCanceller = null;
$scope.loading = false;
$scope.enter = function() {
cancelTimeout();
$scope.loading = true;
};
$scope.leave = function() {
timeoutCanceller = $timeout(function() {
$scope.loading = false;
}, 3000);
};
function cancelTimeout() {
if (timeoutCanceller) $timeout.cancel(timeoutCanceller);
}
});
Here is a working demo.
编辑:将这些事件绑定到父容器而不是直接绑定到元素上可能也是一个好主意。如果该加载程序是一个覆盖,则可能会意外调用 mouseleave 事件。还为您提供了更多样式选择。
<div ng-app="myApp" ng-controller="myController">
<div ng-mouseenter="enter()" ng-mouseleave="leave()">
<div class="mousemove"></div>
<div class="show" ng-show="loading"></div>
</div>
</div>