您的位置:首页 > Web前端 > AngularJS

Angular结合$interval控制时间暂停和继续 完整版

2018-01-05 14:44 633 查看
效果图:



------------------------------------------------------------------------------------------------------------------------------

1、网上不正常的

<body ng-app="App">
<div ng-controller="DemoCtrl">
<p>当前时间为: {{now|date:'yyyy-MM-dd hh:mm:ss'}}</p>
<button ng-click="stop()">停止</button>
<button ng-click="start()">开始</button>
</div>
<script>
var App = angular.module('App', []);
App.controller('DemoCtrl', ['$scope', '$timeout', '$interval', function ($scope, $timeout, $interval) {
$scope.now = new Date();
var timer = $interval(function () {
$scope.now = new Date();
}, 1000);

$scope.stop = function () {
$interval.cancel(timer);
}
$scope.start = function () {
timer;
}
}])
</script>

2、自己研究出来的

<body ng-app="App" ng-controller="DemoCtrl" ng-init="start()">
<div>
<p>当前时间为: {{now|date:'yyyy-MM-dd HH:mm:ss'}}</p>
<button ng-click="stop()">停止</button>
<button ng-click="start()">继续</button>
</div>
<script>
var App = angular.module('App', []),
timer;
App.controller('DemoCtrl',function ($scope, $interval) {
$scope.now = new Date();
$scope.start=function(){
//stop();
timer = $interval(function () {
$scope.now = new Date();
}, 1000);
$scope.stop = function () {
$interval.cancel(timer);
}
}
})
</script>

总结:自己想想什么原因吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: