【发布时间】:2016-04-09 06:51:35
【问题描述】:
我在视图控制器中完成了一些 javascript 编码。
我第一次访问该路线时,它按预期工作,但是当我转到另一条路线并返回它时,javascript 似乎执行了两次,并且我所做的效果被搞砸了(加倍)。
这是我的代码:
'use strict'
angular.module('myApp')
.controller('FuncionesCtrl', function($scope) {
$scope.viewName = 'Funciones';
var count = 0;
var array = [
'identificada',
'en espera',
'entre tres'
];
$('#teasers').html(array[0]);
setInterval(function (){
if(count == 2) {
console.log('if');
count = 0;
$('#teasers').slideUp(500);
setTimeout(function (){
$('#teasers').html(array[count]);
},500);
$('#teasers').slideDown(500);
} else {
console.log('else');
count ++;
$('#teasers').slideUp(500);
setTimeout(function (){
$('#teasers').html(array[count]);
},500);
$('#teasers').slideDown(500);
}
}, 2000);
});
这是一个动画,其中字符串向上滑动(消失),然后作为不同的单词向下滑动。第一次效果不错,但我再次访问路线后,动画似乎加快了。
我该如何解决这个问题?
谢谢!
编辑
我做了一些改动:
'use strict'
angular.module('myApp')
.controller('FuncionesCtrl', function($scope, $interval) {
$scope.viewName = 'Funciones';
clearInterval(interval);
var count = 0;
var array = [
'identificada',
'en espera',
'entre tres'
];
$('#teasers').html(array[0]);
var interval = setInterval(function (){
if(count == 2) {
console.log('if');
count = 0;
$('#teasers').slideUp(500);
setTimeout(function (){
$('#teasers').html(array[count]);
},500);
$('#teasers').slideDown(500);
} else {
console.log('else');
count ++;
$('#teasers').slideUp(500);
setTimeout(function (){
$('#teasers').html(array[count]);
},500);
$('#teasers').slideDown(500);
}
}, 2000);
});
clearInterval 似乎什么也没做。
解决方案
我已经弄明白了:
'use strict'
angular.module('myApp')
.controller('FuncionesCtrl', function($scope, $interval) {
$scope.viewName = 'Funciones';
// clearInterval(interval);
var count = 0;
var array = [
'identificada',
'en espera',
'entre tres'
];
$('#teasers').html(array[0]);
var interval = $interval(function (){
if(count == 2) {
console.log('if');
count = 0;
$('#teasers').slideUp(500);
setTimeout(function (){
$('#teasers').html(array[count]);
},500);
$('#teasers').slideDown(500);
} else {
console.log('else');
count ++;
$('#teasers').slideUp(500);
setTimeout(function (){
$('#teasers').html(array[count]);
},500);
$('#teasers').slideDown(500);
}
}, 2000);
$scope.$on('$destroy', function (e){
$interval.cancel(interval);
});
});
这个:
$scope.$on('$destroy', function (e){
$interval.cancel(interval);
});
成功了。
【问题讨论】:
-
使用 $interval 和 $timeout 角度服务
标签: javascript jquery angularjs