你好我想用户使用AngularJS为用户制作一条实时消息,并且我使用间隔使消息来自数据库自动/无需重新加载页面,但间隔每次都重新加载而无法停止。
我希望在数据到达时停止间隔。下面这条消息是我的代码
<div class="col-lg-12 wt-rounded-edge set-nego-chat-box" pesan id="show-pesan">
<!-- list of the message-->
</div>
// the input and button
<textarea ng-model="databaru.pesan"></textarea>
<input type="text" ng-model="databaru.pesanwaktu">
<button ng-click="tambahData()">Sent</button>
var test = angular.module('tesApp', ['ngRoute', 'angularMoment']);
test.factory('factoryPesan', function($http) {
var factoryPesan = {};
factoryPesan.getPesan = function() {
return $http.get('get_data.php');
};
factoryPesan.putPesan = function($datas) {
return $http.post('add_data.php', $datas);
};
return factoryPesan;
});
/*--------------get the data--------------*/
test.directive('pesan', function() {
return {
restirct: 'A',
templateUrl: 'mymessage.php',
controller: function($scope, factoryPesan, $interval, $timeout) {
/*--------------------my interval start here----------------------------------*/
$scope.getData = function() {
factoryPesan.getPesan().success(function(hasil) {
$scope.data = hasil;
});
};
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getData();
$scope.intervalFunction();
}, 3000)
};
$scope.intervalFunction();
}
};
});
/* -------------------------end of interval-----------------------*/
/*--------------controller to put the data in database--------------*/
test.controller('livechat', function($scope, $timeout, $http, factoryPesan, dataService) {
$scope.tambahData = function() {
databaru = {
pesan: $scope.databaru.pesan,
pesanwaktu: $scope.databaru.pesanwaktu
};
factoryPesan.putPesan(databaru).success(function(hasil) {
$scope.data.push({
pesan: $scope.databaru.pesan,
pesanwaktu: $scope.databaru.pesanwaktu
});
$scope.databaru.pesan = '';
$scope.status = 'oke';
});
};
});
如何解决这个问题,重点是如何在数据库中有新数据时重新加载,并在新数据到达时停止。