<!DOCTYPE html> <html ng-app="myApp"> <head lang="en"> <meta charset="UTF-8"> <script src="js/angular.js"></script> <title></title> </head> <body> <div ng-controller="myCtrl"> <span>{{count}}</span> </div> <script> var app = angular.module('myApp', ['ng']); app.controller('myCtrl', function ($scope, $interval) { $scope.count = 0; //启动周期性定时器 实现对数据的自增操作 /* setInterval( function () { $scope.count++; console.log($scope.count); //$scope.$digest(); $scope.$apply(); }, 500 )*/ $interval( function () { $scope.count++; }, 500) }) </script> </body> </html>
通过$interval,每隔1s,实现图片轮播,两个按钮:开始、结束
分析:
构造数组,数组中存储是图片的名称信息
通过定时器不断的切换数组的下标。
结果:
<!DOCTYPE html> <html ng-app="myApp"> <head lang="en"> <meta charset="UTF-8"> <script src="js/angular.js"></script> <title></title> </head> <body> <div ng-controller="myCtrl"> <img ng-src="img/{{list[index]}}" alt=""/> <button ng-click="start()">开始</button> <button ng-click="stop()">结束</button> </div> <script> var app = angular.module('myApp', ['ng']); app.controller( 'myCtrl', function ($scope,$interval) { $scope.index = 0; $scope.list = ['1.jpg','2.jpg','3.jpg','4.jpg']; $scope.start = function () { //启动定时器 promise = $interval( function () { $scope.index++; if($scope.index > 3 ) { $scope.index = 0; } }, 500 ) } $scope.stop = function () { //结束定时器 $interval.cancel(promise); } }) </script> </body> </html>