how to pass the dynamic variable to setInterval method - javascript

i want to refresh/reload the method in every 30 seconds. but im not able to send the variable data to another function i.e setInterval.how to pass variable in the setInterval method.while adding static variable its working but how can i pass the id to setInterval method
var app = angular.module('PIR_Detection', []);
app.controller('myCtrl', function ($scope, $http, $window) {
$scope.sel_val = 0;
$scope.DefaultLabel = "Loading.....";
var post = $http({
method: "get",
url: "../data.json",
dataType: 'json',
data: {},
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$scope.Customers = data;
});
post.error(function (data, status) {
});
$scope.getPIRData = function (id) {
var url = "/PIRDetails/GetPIRStatus/" + id;
$http.get(url)
.then(function (response) {
$scope.myWelcome = response.data;
$scope.pirstatus = base64toHEX($scope.myWelcome.dataFrame);
$scope.timestamp = getIST (response.data.timestamp);
$scope.rssi = response.data.rssi;
deviceid = id;
});
};
setInterval(function () {
$scope.getPIRData("100010102");//unable to pass id here
}, 30000)
});

you can do it in various way,
example:
//set data
window.deviceId=Id
and use it in settimout
setInterval(function () {
$scope.getPIRData(window.deviceId);//unable to pass id here
}, 30000)
but you can declare any global variable of the settimeout outer scope, then that variable will be available into the settimeout call back function, because then it will be treated as Closures

Courtesy of #tvanfosson:
You probably want to have a function that creates the interval timer for you. Pass in the parameter to the function so its value is captured in the function closure and retained for when the timer expires.
function createInterval(f,dynamicParameter,interval) { setInterval(function() { f(dynamicParameter); }, interval); }
Then call it as createInterval(funca,dynamicValue,500); Obviously you can extend this for more than one parameter. And, please, use more descriptive variable names. :)

Related

angular js function value is undefined out side the function

I am using angular js for my project. Currently I am getting data using below function. This is my function.
$scope.loadMoreDetails = function () {
$http({
method: "GET",
url: appConfig.apiUrl + "/results/" + $scope.resultId + "/details/"
}).then(function (response) {
$scope.sourceData = response.data.sources;
$scope.sourceList = $scope.sourceData.split(', '); // split string on comma space
console.log($scope.sourceList);
}, function (response) {
$log.error(response);
});
};
My console log inside the function is working well, but I am trying to access that $scope.sourceList in another function.
$scope.saveAp = function () {
console.log($scope.sourceList)
}
This console.log is undefined. Actually I need to know, how I access $scope.sourceList outside the function. How I do it.

how to refresh method in every 30 seconds using setinterval in angular js [duplicate]

This question already has answers here:
how to pass the dynamic variable to setInterval method
(2 answers)
Why are AngularJS $http success/error methods deprecated? Removed from v1.6?
(2 answers)
Closed 3 years ago.
I have dropdown list, in ng-change event calling ajax call and showing some data but I need the method to execute every 30 seconds. so that i can updated value in every 30 sec
I did refresh mechanism but there are several requests are calling instead
of 1.
first time its triggering 1 time after that its triggering double of
earlier no of requests like 1, 2, 4, 8, 16, 32,64 times requests are
executing
Select PIR Device
Select PIR Device
<th> <select class="form-control ng-pristine ng-valid ng-scope ng-empty ng-touched" ng-model="sel_val" ng-change="getPIRData(sel_val.deveui)" ng-options="data.deveui for data in Customers">Select PIR Device</select></th>
var app = angular.module('PIR_Detection', []);
app.controller('myCtrl', function ($scope, $http, $window) {
$scope.sel_val = 0;
$scope.DefaultLabel = "Loading.....";
var post = $http({
method: "get",
url: "../data.json",
dataType: 'json',
data: {},
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$scope.Customers = data;
});
post.error(function (data, status) {
});
$scope.getPIRData = function (id) {
var url = "/PIRDetails/GetPIRStatus/" + id;
setInterval(function () {
$scope.getPIRData(id);
}, 30000)
$http.get(url)
.then(function (response) {
$scope.myWelcome = response.data;
$scope.pirstatus = base64toHEX($scope.myWelcome.dataFrame);
$scope.timestamp = getIST (response.data.timestamp);
$scope.rssi = response.data.rssi;
});
};
});
The problem here is that you call the setInterval function inside your response process.
Every time your request is processed, you schedule a new function scheduling for every 30 seconds, rather than a new function call every 30 seconds.
$scope.getPIRData = function (id) {
var url = "/PIRDetails/GetPIRStatus/" + id;
$http.get(url)
.then(function (response) {
$scope.myWelcome = response.data;
$scope.pirstatus = base64toHEX($scope.myWelcome.dataFrame);
$scope.timestamp = getIST (response.data.timestamp);
$scope.rssi = response.data.rssi;
});
};
setInterval(function () {
$scope.getPIRData(id);
}, 30000)
I removed the setInterval call from the scope of the response processing. This should now work.

$scope.$watch does not listen in AngularJS 1.6

I have a problem with my script which collects data from database in parts. I would like to inform Angular when downloading data is finished so I used $watch. Unfortunatelly, it does not work. Angular calls function at the beginning instead of after change loadingComplete value.
angular
.module('app')
.controller('tlmController', function($scope, $http) {
var vm = this;
var data = [];
vm.countTestLines = 0;
vm.loadingComplete = false;
$scope.$watch('vm.loadingComplete', function() {
console.log(data);
});
$http({
method: 'GET',
url: 'app/server/tt/count_testlines.php'
}).then(function successCallback(response) {
vm.countTestLines = parseInt(response.data.count);
downloadInParts(data, 0, vm.countTestLines);
}, function errorCallback(response) {
console.log('error');
});
var downloadInParts = function(data, offset, max) {
if(max < offset) {
vm.loadingComplete = true;
return;
}
$http({
method: 'GET',
url: 'app/server/tt/get_testlines.php',
params: { offset: offset }
}).then(function successCallback(response) {
data = data.concat(response.data);
downloadInParts(data, offset + 5, max);
}, function errorCallback(response) {
console.log('error');
});
}
});
The problem is that the loadingComplete is not a part of the scope. you should declare it as $scope.loadingComplete;.
Since you are using 'vm' instead of '$scope', it is a necessary that you need to insert $scope.$apply in your function.
if(max < offset) {
vm.loadingComplete = true;
$scope.$apply();
return;
}
$scope always watches for change in value and if there is any, Angular will call the $digest() function internally and the changed value will be updated. Using 'vm' wont update the value which results in your problem.
If you are using var vm = this, which is the proper way according to JohnPapa's styleguide for AngularJS, you should rewrite your $watch to:
$scope.$watch(function(){ return vm.loadingComplete }, function() {
console.log(data);
});
Update from comments:
Your function parameter data hides your data variable from your controller.

$timeout not working in angular.js

i am using $timeout in my controller but its not working!
app.controller("Friendsrequests",['$http','$log','$location','$timeout','$scope', function($http,$log,$location,$timeout,$scope){
//getting base url of application
this.baseUrl = function() {
var base_url = window.location.origin;
var pathArray = window.location.pathname;
return base_url;
// return base_url+pathArray;
};
// assigning to a variablebase_url('login/f_request');
var ThroughUrl = this.baseUrl()+'/keon/login/f_request';
//declare a variable
var ata = this;
ata.notifications = [ ] ;
ata.counts=' ';
//sending ajax request
function getNotifications()
{
$http({method: 'POST', url: ThroughUrl,})
.success(function(data) {
// this callback will be called asynchronously
// when the response is available
//assign data to the variable
ata.notifications=data;
ata.counts =data.length;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
$timeout(function() {
getNotifications();
}, 1000);
}]);
what is the issue .
UPDATED
Just replace
$timeout(function() {
getNotifications();
}, 1000);
with
$interval(function() {
getNotifications();
},1000);
Check Angular's doc
while calling timeout in angularJS just remove Parentheses or brackets ()
$timeout(getNotifications, 1000);
getNotifications function will call after 1000 milliseconds(One second)

JavaScript module that uses AJAX to set and return variables

I'm trying to write a module that makes two AJAX calls and sets variables to the results of those calls. I'd like to be able to access the results of those calls like myModule.firstCall and get the result of the AJAX call and not the promise.
var ajaxModule = (function () {
var subFolderData = {},
rootData = {};
var subFolderFile = function () {
return $.ajax({
url: 'Content/testData.json',
dataType: 'json'
});
}
var rootFile = function () {
return $.ajax({
url: 'testDataRoot.json',
dataType: 'json'
});
}
//only returning promise here, how to return $.when the call is done?
return {
rootFile: rootFile().done(function (data) {
subFolderData = data;
}),
subFolderFile: subFolderFile().done(function (data) {
rootData = data;
})
}
})();
//this prints out the dat as expected, but can I store the results in a variable
//to be accessed like ajaxModule.rootFile?
console.log(ajaxModule.rootFile.done(function (data) {
console.log(data);
}));
No, you cannot return the result from an asynchronous call.
Assigning them to a global (or higher-scope) variable, such as subFolderData or rootData in your example, is possible, but does not make sense because you do not know when the value will be available.
Storing the promises for the values, like your ajaxModule.subFolderFile and ajaxModule. rootFile, and always incorporating them when needing to access the data, is the way to go.

Categories

Resources