以角度定期调用函数

时间:2016-08-24 10:59:30

标签: javascript angularjs

我有一个角度控制器,可显示背景图像和文字信息。控制器是:

var myArchiveController = function($scope) {

     var setBackground = function() {
         $scope.backgroundUrl = someUrlFromService;
         $scope.backgroundMessage = someMessageFromService;
     }

     setBackground();
}

app.controller("myController", myController);

如何定期调用setBackground()功能,例如每一分钟?

2 个答案:

答案 0 :(得分:6)

使用角度$ interval服务:

var myArchiveController = function($scope, $interval) {

    var setBackground = function() {
        $scope.backgroundUrl = someUrlFromService;
        $scope.backgroundMessage = someMessageFromService;
    }

    $scope.intervalIstance = $interval(setBackground, 60000);
} 

要任意停止,请使用$ interval.cancel。

$interval.cancel($scope.intervalIstance);

不要忘记将$ interval包含在您的依赖项中。

答案 1 :(得分:2)

以下内容应该为您完成。

body{
text-decoration: none;
margin: 0 auto;
max-width:100% !important;
height:auto;}

.fundo img{
max-width:100% !important;
height:auto;}

.menuleft {
background-color: #CDD0D2;
list-style-type: none;
position: relative;
width: 9%;
height: 100%;
display:inline-block;
}

.menuleft ul{
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
vertical-align: middle;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}

#text {
-webkit-box-shadow: inset -7px 4px 5px 0px rgba(0,0,0,0.22);
-moz-box-shadow: inset -7px 4px 5px 0px rgba(0,0,0,0.22);
box-shadow: inset -7px 4px 5px 0px rgba(0,0,0,0.22);
width: 100%;
height: 17%;
color: white;
text-align: center;
text-decoration: none;
background-color: #F06D22;
}

.menuleft li a {
font-family: Futura LT,'Trebuchet MS', Arial;
letter-spacing: 0.28vw;
color: #fff;
text-decoration: none;
height: 100%;
text-align: center;
display: flex;
vertical-align: middle;
align-items: center;
justify-content: center;
width: 100%;
writing-mode: tb-rl;
-webkit-transform:rotate(180deg);
-moz-transform:rotate(180deg);
-o-transform: rotate(180deg);
-ms-transform:rotate(180deg);
transform: rotate(180deg);
white-space:nowrap;
}

.menuleft li:hover {
text-decoration: none;
background: rgba(255,255,255,0.2);
}

.menuleft li a:hover {
text-decoration: none;
color: #fff;
}

#whitebar{
text-decoration: none;
display: table;
width: 100%;
height: 3px;
background-color: #fff;
writing-mode:tb-rl;
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform:rotate(90deg);
transform: rotate(180deg);
white-space:nowrap;
bottom:0;
margin: 0 auto;
}

.image {
width: 90%;
height:100%;
display:inline-block;
}

.image img {
width: 100%;
height: 100%;
}

或者首选方法,是使用有角度的setInterval(setBackground, 60000); 服务 - $interval

您需要将间隔服务($interval(setBackground, 60000);)注入控制器,然后代码如下:

$interval