How can I call $http.get every second to update my page?
var app = angular.module("CompanionApp", []);
app.controller('LoginController', function ($scope, $http) {
$scope.LoginSubmit = function() {
$http.get('/api/player/' + $scope.name)
.then(function(res) {
$scope.connected = res.data.connected;
$scope.health = res.data.health;
$scope.armour = res.data.armour;
})
};
});
Try $interval :
var app = angular.module("CompanionApp", []);
app.controller('LoginController', function ($scope, $http, $interval) {
var interval;
$scope.LoginSubmit = function() {
interval = $interval(function () {
$http.get('/api/player/' + $scope.name)
.then(function(res) {
$scope.connected = res.data.connected;
$scope.health = res.data.health;
$scope.armour = res.data.armour;
})
}, 1000);
};
$scope.stopCalls = function(){ // incase you want to stop the calls using some button click
$interval.cancel(interval);
}
});
Related
In my application I am constantly updating displayed data which changes on the server using an interval, which loads whenever the controller loads. The controller loads together with the function in the interval when I navigate to a specific site and I would like it to stop when I navigate to another. The problem is that after some time of usage of the site, I end up with a bunch of intervals running and it just appears nasty. Here is the code of the controller:
angular
.module('myApp')
.controller('TaxiesController', ['$scope', '$location', '$routeParams', '$route', 'dataFactory', '$interval', function ($scope, $location, $routeParams, $route, dataFactory, $interval) {
console.log('TaxiesController loaded')
var cancel = {
name: 'Preklic',
price: 500
}
$scope.taxies = [];
$scope.taxi = {};
$scope.taxi.history = [];
taxi = {}
taxi.history = [];
$scope.getTaxies = () => {
dataFactory.getTaxies().then(function (response) {
$scope.taxies = response.data;
});
}
$scope.getTaxi = () => {
var id = $routeParams.id;
dataFactory.getTaxi(id).then(function (response) {
$scope.taxi = response.data;
});
}
$scope.removeTaxi = (id) => {
dataFactory.removeTaxi(id).then(function (response) {});
}
$scope.getTotal = (taxi) => {
var total = 0;
for (var i = 0; i < taxi.history.length; i++) {
var rent = taxi.history[i];
if (rent.price) total += rent.price;
}
return total;
}
$scope.disableTaxi = (taxi, id) => {
taxi.drivable = false;
dataFactory.updateTaxi(id, taxi).then(function (response) {
$scope.taxi = response.data;
$route.reload();
})
}
$scope.cancelTaxi = (taxi, id) => {
console.log('cancelling..')
taxi.available = true;
taxi.history.unshift(cancel);
dataFactory.updateTaxi(id, taxi).then(function (response) {});
}
var updateTaxies = () => {
console.log('Checking rent length')
dataFactory.getTaxies().then(function (response) {
$scope.taxies = response.data;
});
}
$interval(updateTaxies, 2000);
}]);
Just add this inside the controller:
var intervalListener = $interval(updateTaxies, 2000);
$scope.$on('$destroy', function() {
$interval.cancel(intervalListener);
});
$destroy is an event that will be fired when a scope is being destroyed. Here is the doc about it
i try to share data between two different controllers using a service and watch changes but i don't find how to do this. Here is my code
month-select.component.js:
'use strict'
angular
.module('myApp.monthSelect')
.component('myApp.monthSelect', {
templateUrl: 'monthSelect/month-select.template.html',
controller: 'MonthSelectCtrl',
css: 'monthSelect/month-select.style.css'
})
.controller('MonthSelectCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
selectedMonthSvc.setDate($scope.dt)
}])
weeks-list.component.js:
'use strict'
angular
.module('myApp.weeksList')
.component('myApp.weeksList', {
templateUrl: 'weeksList/weeks-list.template.html',
controller: 'WeeksListCtrl',
css: 'weeksList/weeks-list.style.css'
})
.controller('WeeksListCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
$scope.getDate = selectedMonthSvc.getDate
}])
get-select-month.service.js
angular.module('myApp.svc', [])
.factory('selectedMonthSvc', function () {
var self = this
var date = ''
self.setDate = function (value) {
return date = value
}
self.getDate = function () {
return date
}
return self
})
It works at init i get the date in my WeeksList controllers, but if i change the date in my MonthSelectCtrl, the value don't update in WeekList.
I'm trying to watch it with $watch but it don't work and have no idea where it goes wrong.
Thank you very much for your help.
1st off change factory to service:
.service('selectedMonthSvc', function () {/**/}
Further
You can write watcher to listen on changes.
So instead:
$scope.getDate = selectedMonthSvc.getDate
try:
$scope.getDate = selectedMonthSvc.getDate;
$scope.$watch('getDate', function() {
// here you get new value
});
This is simple demo that demonstrates your case
When second controller updates date, 1st controller listens and reflects on changes:
angular.module('myApp', [])
.controller('Ctrl1', function ($scope, App) {
$scope.status = App.getDate();
$scope.$watch(function(){
return App.getDate();
}, function() {
$scope.status = App.getDate();
});
})
.controller('Ctrl2', function ($scope, App) {
$scope.status = App.getDate();
$scope.$watch('status', function() {
App.setDate($scope.status);
});
})
.service('App', function () {
this.data = {};
this.data.date = 'someDate';
var self = this;
var date = ''
self.setDate = function (value) {
this.data.date = value
}
self.getDate = function () {
return this.data.date;
}
});
Try this:
// selectedMonthSvc service:
angular.module('myApp.svc', [])
.factory('selectedMonthSvc', function () {
var date = '';
var self = this
self.setDate = setDate;
self.getDate = getDate;
return self;
function setDate(value) {
date = value;
}
function getDate() {
return date;
}
})
// WeeksListCtrl controller
.controller('WeeksListCtrl', ['$scope', 'selectedMonthSvc', function ($scope, selectedMonthSvc) {
$scope.getDate = getDate;
function getDate() {
return selectedMonthSvc.getDate();
}
}])
var app = angular.module('app', []);
app.controller('firstController', ['$scope','selectedMonthSvc', function($scope, selectedMonthSvc) {
$scope.date = new Date();
$scope.changeDate = function() {
selectedMonthSvc.setDate(new Date())
}
}]);
app.controller('secondController', ['$scope','selectedMonthSvc', function($scope, selectedMonthSvc) {
$scope.date = '';
$scope.selectedMonthSvc = selectedMonthSvc;
$scope.$watch(function() {
return $scope.selectedMonthSvc.getDate();
}, function(newVal) {
$scope.date = newVal;
}, true);
}]);
app.factory('selectedMonthSvc', [function() {
var date = '';
return {
getDate: function () {
return date;
},
setDate: function(d) {
date = d;
}
}
}])
Here is the working plunker https://plnkr.co/edit/w3Y1AyhcGhGCzon8xAsV?p=preview
I have an app which fetches data from a database on load.
Since the data in the database changes every few seconds, I would like to dynamically add the new data in the database into the table in the HTML page.
Any ideas on how to implement without reloading the controller?
The current code:
app.js
var app = angular.module('myApp', ['ui.bootstrap','countTo']);
app.filter('startFrom', function() {
return function(input, start) {
if(input) {
start = +start; //parse to int
return input.slice(start);
}
return [];
}
});
app.config(['$compileProvider', function($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|http?|file|data):/);
}]);
app.controller('customersCrtl', function ($scope, $http, $timeout) {
$scope.$emit('LOAD');
$scope.progressBar = { progress : 0 };
$http.get('ajax/getCustomers.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 50; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
$scope.$emit('UNLOAD');
});
(function progress(){
if($scope.progressBar.progress < 100){
$timeout(function(){
$scope.progressBar.progress += 1;
progress();
},5);
}
})();
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
app.controller('delayController',['$scope',function($scope){
$scope.$on('LOAD',function(){$scope.loading=true});
$scope.$on('UNLOAD',function(){$scope.loading=false});
}]);
app.controller("PostsCtrl", function($scope, $http, $timeout) {
$scope.progressBarScanned = { progressScanned : 0 };
(function tick() {
$http.get('ajax/scanStatus.php').
then(function(response) {
$scope.posts = response.data;
$scope.scanProgerss = $scope.posts[0].isScanning;
$scope.scanPercentage = $scope.posts[0].scanPercentage;
$scope.timeToFinish = $scope.posts[0].timeToFinish;
$scope.amountScanned = $scope.posts[0].amountScanned;
$scope.totalItemsToScan = $scope.posts[0].totalItemsToScan;
$scope.avgScanTimePerItem = $scope.posts[0].avgScanTimePerItem;
});
$timeout(tick, 1000);
})();
(function progressScanned(scanned){
if($scope.scanPercentage < 100){
$timeout(function(){
$scope.progressScanned.progress = 1;
progressScanned();
},5);
}
})();
});
//Modal
var ModalDemoCtrl = function ($scope, $modal) {
$scope.open = function (imageKey) {
$modal.open({
templateUrl: 'myModalContent.html',
backdrop: true,
windowClass: 'full',
controller: function ($scope, $modalInstance, data, imageKey) {
$scope.data='';
$scope.data = data;
$scope.getImage = function () {
return $scope.data[imageKey];
}
$scope.cancel = function () {
$modalInstance.dismiss('close');
};
},
resolve: {
data: function() {
// access outer controller scope by using $scope.$parent
return $scope.$parent.data;
},
imageKey: function() {
return imageKey;
}
}
});
}};
I'm an angular newbie and I'm writing an Ionic app.
I finished my app and am trying to refactor my controller avoiding code repetition.
I have this piece of code that manages my modal:
angular.module('starter')
.controller('NewsCtrl', function($scope, content, $cordovaSocialSharing, $timeout, $sce, $ionicModal){
$scope.news = content;
content.getList('comments').then(function (comments) {
$scope.comments = comments;
});
$scope.addComment = function() {
};
$scope.shareAnywhere = function() {
$cordovaSocialSharing.share("Guarda questo articolo pubblicato da DDay", "Ti stanno segnalando questo articolo", content.thumbnail, "http://blog.nraboy.com");
};
$ionicModal.fromTemplateUrl('templates/comments.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.showComment = function() {
$scope.modal.show();
};
// Triggered in the login modal to close it
$scope.closeComment = function() {
$scope.modal.hide();
};
$scope.$on('modal.shown', function() {
var footerBar;
var scroller;
var txtInput;
$timeout(function() {
footerBar = document.body.querySelector('#commentView .bar-footer');
scroller = document.body.querySelector('#commentView .scroll-content');
txtInput = angular.element(footerBar.querySelector('textarea'));
}, 0);
$scope.$on('taResize', function(e, ta) {
if (!ta) return;
var taHeight = ta[0].offsetHeight;
if (!footerBar) return;
var newFooterHeight = taHeight + 10;
newFooterHeight = (newFooterHeight > 44) ? newFooterHeight : 44;
footerBar.style.height = newFooterHeight + 'px';
scroller.style.bottom = newFooterHeight + 'px';
});
});
});
I have added this same code in 6 controllers.
Is there a way to avoid the repetition?
Probably what you are looking for is an angular service. This component is a singleton object, that you inject in every controller you need to execute this code.
Angular Services
Regards,
Below is an example of a service I created to retrieve address data from a Json file. Here is the working Plunk. http://plnkr.co/edit/RRPv2p4ryQgDEcFqRHHz?p=preview
angular.module('myApp')
.factory('addressService', addressService);
addressService.$inject = ['$q', '$timeout', '$http'];
function addressService($q, $timeout, $http) {
var addresses = [];
//console.log("Number of table entries is: " + orders.length);
var promise = $http.get('address.data.json');
promise.then(function(response) {
addresses = response.data;
// console.log("Number of table entries is now: " + orders.length);
});
return {
GetAddresses: getAddresses
};
function getAddresses() {
return $q(function(resolve, reject) {
$timeout(function() {
resolve(addresses);
}, 2000);
});
}
}
Here's an example of how I added dependencies for it and another service to my controller (This is NOT the only way to do dependency injection, but is my favorite way as it is easier to read). I then called my addressService.GetAddresses() from within my controller.
var app = angular.module('myApp', ['smart-table']);
app.controller('TableController', TableController);
TableController.$inject = [ "orderService", "addressService"];
function TableController( orderService, addressService) {
addressService.GetAddresses()
.then(function(results) {
me.addresses = results;
// console.log(me.addresses.length + " addresses");
},
function(error) {})
.finally(function() {
me.loadingAddresses = false;
});
});}
I also had to include my .js tag in a script element on my index.html.
<script src="addressdata.service.js"></script>
I have an AngularJS 1.2 app. My app has a controller that looks like this:
myApp.controller('MyController', ['$scope', '$rootScope', '$http',
function ($scope, $rootScope, $http) {
$scope.newItem_Click = function () {
var modalInstance = $modal.open({
templateUrl: 'item-dialog.html',
size: 'md',
controller: function ($scope, $modalInstance) {
$scope.item = { typeId: 7, id: '-1' };
$scope.saveItem = function (did) {
if ($scope.item.description) {
if ($scope.item.description.trim().length > 0) {
$scope.item.departmentId = did;
$modalInstance.close($scope.item);
}
} else {
alert('Please enter your description.');
}
};
$scope.cancelItem = function () {
$modalInstance.dismiss('cancel');
};
$scope.getItems = function (departmentId) {
var url = '/api/items?departmentId=' + departmentId;
return $http.get(url).then(
function (response) {
var results = response.data;
results.reverse();
var items = [];
var i = 0;
angular.forEach(results, function (item, key) {
var local = results[i].CreatedUTC;
results[i].CreatedOn = new Date(local);
items.push(item);
i = i + 1;
});
console.log(items);
$scope.items = items;
}
);
};
$scope.$on('list-updated', function () {
$scope.getItems($scope.item.id);
});
}
});
modalInstance.result.then(
function (item) {
var apiUrl = '/api/items';
apiUrl = apiUrl + '?typeId=' + item.typeId;
if (item.departmentId!== '-1') {
apiUrl = apiUrl + '&departmentId=' + item.departmentId;
}
apiUrl = apiUrl + '&content=' + item.description;
apiUrl = encodeURI(apiUrl);
$http.post(apiUrl).then(
function () {
$rootScope.$broadcast('list-updated');
}
);
}
);
};
}]);
For some reason, I can successfully save an item. The console.log(items) statement displays all of the items as I would expect. However, my view is not being updated. What am I doing wrong? I suspect its because I'm assigning $scope.items inside of the HTTP response. Yet, I'm not sure how to get around it.
I know this is not recommended. However, I am in crunch mode.