Reputation: 183
I have a scenario where i need to show a div when a user provides input.
When a user continuously changes the input value the div must be shown and when the user stops providing input after 5 secs or so the div must be hidden.
Ctrl :
function MainCtrl($scope,$timeout) {
$scope.appear = false;
$scope.showDiv = function() {
debugger;
$scope.appear = true;
}
$scope.$watch('appear',
function(newValue, oldValue) {
if(newValue && newValue===true){
$timeout(function(){
$scope.appear=false;
}, 5000);
}
}
);
}
html:
<body ng-controller="MainCtrl">
Name: <input type="text" ng-change="showDiv()" ng-model="inputText"/> <br/>
<div ng-show="appear">Content</div>
</body>
The issue i am facing here is when i continuously provide input the div at some point of time it is getting hidden and reappearing again.
But I need the div to be shown till the input is being provided and when a user stops providing any input after 5 secs it should disappear.
Any help would be appreciated.
Upvotes: 1
Views: 60
Reputation: 683
I got below code working :
$scope.showDiv = function () {
alert(1);
$('#divShow').show();
setTimeout("$('#divShow').hide();", 5000);
}
Write this in the controller and give that "divShow"
id to div and remove ng-show thing.
This worked for me, Hope help you.
Upvotes: 0
Reputation: 4700
You should clear your timeout: https://plnkr.co/edit/wY4C1wvBZKJ7RSwtgnCv?p=preview
angular.module('plunker', []);
function MainCtrl($scope,$timeout) {
var timeout;
$scope.appear = false;
$scope.showDiv = function() {
// debugger;
$scope.appear = true;
if(timeout) {
console.log('timeout')
$timeout.cancel(timeout);
}
timeout = $timeout(function(){
$scope.appear=false;
}, 5000);
}
}
Upvotes: 1
Reputation: 681
I have made some changes to your plunkr, check this link https://plnkr.co/edit/EsiG3Ifgk0maYF4GJTGm?p=preview
angular.module('plunker', []).controller('MainCtrl',function($scope,$timeout) {
$scope.appear = false;
$scope.timerId;
$scope.showDiv = function() {
if($scope.timerId!=undefined){
clearTimeout($scope.timerId);
}
$scope.appear = true;
$scope.timerId = $timeout(function(){
$scope.appear=false;
},5000);
}
});
Upvotes: 2