我不知道为什么我点击按钮后间隔不能用于HTML。我使用angularJS来计算每一秒。我只想在点击按钮后启动间隔。
此 HTML
<button type="button" ng-click="start()"><span>Start {{hitung}}</span></button>
这个 JS
$scope.hitung = 0;
$scope.start= function () {
var auto = $interval(function () {
$scope.hitung++;
}, 1000);
};
我试试这个,但是间隔不起作用$scope.hitung always 0
。如果有人有解决方案,请告诉我这对我有帮助。
由于
答案 0 :(得分:1)
这是一个使用更现代风格的AngularJS开发的工作解决方案(需要AngularJS v1.5或更高版本):
angular.module('stackoverflow', [])
.component('counter', {
template: '<button type="button" ng-click="$ctrl.start()"><span>Start {{$ctrl.hitung}}</span></button>',
controller: ['$interval', function CounterCtrl($interval) {
var self = this;
this.hitung = 0;
var interval;
var cancelInterval = function() {
if (!interval) return;
$interval.cancel(interval);
interval = null;
};
this.start = function() {
cancelInterval();
interval = $interval(function() {
self.hitung++;
}, 1000);
};
this.$onDestroy = function() {
$interval.cancel(interval);
};
}]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="stackoverflow">
<counter></counter>
</div>
答案 1 :(得分:0)
试试这个。
$scope.hitung = 0;
$scope.start= function () {
$interval(function () {
$scope.hitung++;
}, 1000);
};
答案 2 :(得分:0)
我检查了你的代码,发现它运作良好。也许你错过$interval
控件中的controllers
参数。
尝试按以下方式添加$ interval ...
//There app is an `angular.module` and `myCtrl` is a `controller`
app.controller('myCtrl', function($scope, $interval) {
$scope.hitung = 0;
$scope.start= function () {
var auto = $interval(function () {
$scope.hitung++;
}, 1000);
};
});