AngularJs: Priorities controlles calls in angularJs - angularjs

I am facing problem on angularJs calendar. Basically I am using Angular-UI calendar So I have created a controller called "CalendarController" in this controller I am calling service and getting data using ajax call... but I don't know why its happening, When page is loading it goes into directly calendar config line and then it goes for the service ajax call. So can anyone have some solution for this.
Goal: Need to priorities the controller calls e.g. if I have 2 controllers Ctrl1 and Ctrl2, then if I want call Ctrl2 and after then Ctrl1 will call.
'use strict';
/* Controllers */
angular.module('myApp', ['myApp.services','myApp.directives','myApp.filters','ui.bootstrap', '$strap.directives']).
controller('navCtrl', function($scope) {
console.log("### navController");
}).
controller('ContactController', function($scope, contactFactory) {
console.log("### ContactController is called");
/**
* Getting Contact detail
**/
$scope.contacts = [];
contactFactory.getContacts().success(function(response){
$scope.contacts = response.data;
console.log("### Getting Contact data");
console.log($scope.contacts);
});
}).
controller('ActivityController', function($scope, activityFactory) {
$scope.oneAtATime = true;
$scope.loading = true;
activityFactory.getNotifications().success(function(response){
var activityData = [];
var total = parseInt(response.data.length);
for (var i=0; i<total; i++)
activityData.push(response.data[i].desc);
$scope.activities = activityData;
console.log("### Getting Activity data");
console.log($scope.activities);
$scope.loading = false;
});
}).
controller('CalendarController', function($scope, contactFactory, calendarFactory) {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
/* event source that pulls from google.com */
$scope.eventSource = {
editable: true,
className: 'gcal-event', // an option!
currentTimezone: 'America/Chicago' // an option!
};
/* event source that contains custom events on the scope */
/**
* Getting Staff detail
**/
$scope.staff = [];
var staffDetail = {};
contactFactory.getStaff().success(function(response){
var staffData = response.data;
if(staffData!=null) {
var total = parseInt(staffData.length);
for (var i=0; i<total; i++) {
staffDetail = {
'id': staffData[i].staffId,
'name': staffData[i].name,
};
$scope.staff.push(staffDetail);
}
}
console.log("### Getting Staff data");
console.log($scope.staff);
});
var calDailyEvents = {};
$scope.events = [];
calendarFactory.getCalendarDailyEvents().success(function(response){
var eventData = response.data;
console.log("### getCalendarDailyEvents");
if(eventData!=null) {
var total = parseInt(eventData.length);
for (var i=0; i<total; i++) {
var totalStaff = eventData[i].eventAssignedToForms.length;
var staffIds = [];
for(var j=0;j<totalStaff;j++) {
staffIds.push(eventData[i].eventAssignedToForms[j].contactId);
}
console.log(staffIds);
calDailyEvents = {
'id': eventData[i].id,
'title': eventData[i].eventName,
'start': Date(eventData[i].startDate),
allDay: false,
resource: staffIds
};
$scope.events.push(calDailyEvents);
}
}
console.log("### Getting DailyEvents data");
console.log($scope.events);
});
/* event source that calls a function on every view switch */
$scope.eventsF = function (start, end, callback) {
/*Commented for testing purpose*/
/* var s = new Date(start).getTime() / 1000;
var e = new Date(end).getTime() / 1000;
var m = new Date(start).getMonth();
var events = [{title: 'Feed Me ' + m,start: s + (50000),end: s + (100000),allDay: false, className: ['customFeed']}];
callback(events); */
};
/* alert on eventClick */
$scope.alertEventOnClick = function( calEvent, jsEvent, view ){
$scope.$apply(function(){
$scope.alertMessage = ('Event: ' + calEvent.title);
$scope.alertMessage += ('View: ' + view.name);
});
};
$scope.onEventRender = function(event, element) {
console.log("### onEventRender");
};
$scope.onDayClick = function( date, allDay, jsEvent, view ){
$scope.$apply(function(){
$scope.alertMessage = ('Day Clicked ' + date);
});
//$scope.$popover();
};
/* alert on Drop */
$scope.alertOnDrop = function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view){
$scope.$apply(function(){
$scope.alertMessage = ('Event Droped to make dayDelta ' + dayDelta);
});
};
/* alert on Resize */
$scope.alertOnResize = function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ){
$scope.$apply(function(){
$scope.alertMessage = ('Event Resized to make dayDelta ' + minuteDelta);
});
};
/* add and removes an event source of choice */
$scope.addRemoveEventSource = function(sources,source) {
var canAdd = 0;
angular.forEach(sources,function(value, key){
if(sources[key] === source){
sources.splice(key,1);
canAdd = 1;
}
});
if(canAdd === 0){
sources.push(source);
}
};
/* add custom event*/
$scope.addEvent = function() {
$scope.events.push({
title: 'Open Sesame',
start: new Date(y, m, 28),
end: new Date(y, m, 29),
className: ['openSesame']
});
};
/* remove event */
$scope.remove = function(index) {
$scope.events.splice(index,1);
};
/* Change View */
$scope.changeView = function(view) {
$scope.myCalendar.fullCalendar('changeView',view);
};
/* config object */
$scope.uiConfig = {
calendar:{
height: 450,
editable: true,
header:{
left: 'prev,next',
center: 'title',
right: 'resourceDay, agendaWeek, resourceWeek',
},
resources: $scope.contacts,
allDaySlot: false,
defaultView: 'resourceDay',
dayClick: $scope.onDayClick,
eventClick: $scope.alertEventOnClick,
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.onEventRender
}
};
console.log($scope.contacts);
/* event sources array*/
$scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
});

Related

Only getting a few markers in the map

I am very new to angularJS and still exploring.I have created a map and showing around 1500 markers in it but when I load only 11 markers are visible.I am taking the Zip codes from a XML file and using geocoding I am converting them to LatLng and showing in map.Can any one suggest any solution.
Thanks in advance.
//Angular App Module and Controller
var mapApp = angular.module('mapApp', []);
// app.directive("importSheetJs", [SheetJSImportDirective]);
mapApp.factory('mySHaredService', function ($rootScope) {
var mySHaredService = {};
mySHaredService.message = '';
mySHaredService.prepForBroadcast = function (msg) {
this.message = msg;
this.broadcastItem();
};
return mySHaredService;
});
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
$timeout(function() {
console.log("Zip data from excel sheet" + $rootScope.zipArray)
var geocoder = new google.maps.Geocoder();
for (var i = 15; i <= $rootScope.zipArray.length; i++) {
var address = $rootScope.zipArray[i];
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
$rootScope.LatLongList.push({
"latitudeValue": latitude,
"longitudeValue": longitude
});
}
});
}
// setTimeout(function () {
// $scope.$apply(function () {
// })
// }, 30000);
$timeout(function () {
console.log("Latitude value " + $rootScope.LatLongList[1].latitudeValue)
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(33.6496252, -117.9190418),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
$scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
var circle = new google.maps.Circle({
center: new google.maps.LatLng(33.6496252, -117.9190418),
map: $scope.map,
radius: 10000, // IN METERS.
fillColor: '#FF6600',
fillOpacity: 0.3,
strokeColor: "#FFF",
strokeWeight: 0 // DON'T SHOW CIRCLE BORDER.
});
var bounds = circle.getBounds();
$scope.markers = [];
$rootScope.selectedAd = "";
var selectedLocation = [{ "lat": 0, "long": 0 }];
var infoWindow = new google.maps.InfoWindow();
var createMarker = function (info) {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.maps.LatLng(info.latitudeValue, info.longitudeValue),
title: ""
});
marker.content = '<div class="infoWindowContent">' + '<br />' + info.latitudeValue + ' E,' + info.longitudeValue + ' N, </div>';
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent('<h2>' + marker.title + '</h2>' +
marker.content);
infoWindow.open($scope.map, marker);
selectedLocation[0].lat = marker.getPosition().lat();
selectedLocation[0].long = marker.getPosition().lng();
console.log("Latitude is " + selectedLocation[0].lat + "Longitude is " + selectedLocation[0].long);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
latLng: marker.getPosition()
}, $scope.selectedLoc = function (responses) {
if (responses && responses.length > 0) {
// alert(responses[0].formatted_address);
$rootScope.selectedAd = responses[0].formatted_address;
setTimeout(function () {
$scope.$apply(function () {
$rootScope.selectedAd = responses[0].formatted_address;
})
}, 1000);
$timeout(function () {
$rootScope.selectedAd = responses[0].formatted_address;
$scope.handleClick = function (msg) {
mySHaredService.prepForBroadcast($rootScope.selectedAd);
}
$scope.$on('handleBroadcast', function () {
$scope.message = $rootScope.selectedAd;
})
}, 2000);
} else {
}
});
});
$scope.markers.push(marker);
}
setTimeout(function () {
}, 3000);
$timeout(function () {
for (i = 1; i < $rootScope.LatLongList.length; i++) {
console.log(bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue)));
// if (bounds.contains(new google.maps.LatLng($rootScope.LatLongList[i].latitudeValue, $rootScope.LatLongList[i].longitudeValue))) {
createMarker($rootScope.LatLongList[i]);
console.log("The value of i is " + i);
// }
}
}, 4000);
$scope.openInfoWindow = function (e, selectedMarker) {
var data = $rootScope.selectedAd
this.broadcastItem();
window.location = "valuePage.html";
}
}, 4000);
}, 2000);
oReq.send();
});
mapApp.controller("viewApp", function ($scope, $rootScope, mySHaredService, $timeout) {
// $scope.selectedAd = Products.FirstName;
// $scope.selectedAd = Products.FirstName;
setTimeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 3000);
$timeout(function () {
$scope.$on('handleBroadcast', function () {
$scope.message = mySHaredService.message;
});
}, 4000);
});
This is because you are sending too many requests through per second.
In addition to daily quota limits, the geocoding service is rate limited to 50 QPS (queries per second), calculated as the sum of client-side and server-side queries.
The Optimizing Quota Usage When Geocoding has a lot of strategies on how to account for that.
In your case I suggest doing a randomized interval for each request you make that way they are spread out you avoid going over the 50 request per second limit.
I've modified the part of your code sample where you are making the request.
mapApp.controller('MapController', function ($scope, $timeout, $window, $rootScope, mySHaredService) {
//Parsing data from XML
$rootScope.zipArray = [];
var url = "location.xlsx";
var randomTime = Math.round(Math.random()*(3000-500))+500;
var geocodeRequest = setTimeout(function() {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
$rootScope.LatLongList = [{
"latitudeValue": "",
"longitudeValue": ""
}];
oReq.onload = function (e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, { type: "binary" });
var first_sheet_name = workbook.SheetNames[0];
var address_of_cell = "K1";
var worksheet = workbook.Sheets[first_sheet_name];
data = JSON.stringify(XLSX.utils.sheet_to_json(worksheet));
console.log("Messege data" + data);
var finalData = JSON.parse(data);
for (var i = 0; i <= finalData.length; i++) {
// console.log("Zip code is " + finalData[i].Zip);
$rootScope.zipArray.push(finalData[i].ZIP);
console.log("Zip code inside zip array is " + $rootScope.zipArray[i]);
}
}
setTimeout(function () {
$scope.$apply(function () {
})
}, 17770);
}, randomTime);

ui-calendar cell background color not displaying for the first time

I am trying to get a list of dates from Rest and change the background color of those dates using dayRender .But when i try to do it the color is not getting changed for the first time.If i go to next month and come back to the month,it will work perfectly.Here are screenshots to make it more clear.
When i load the page
When i move from june to july
When move back to june
Here is my code .rest/leave/holidayList is the rest url for retreiving dates from db.
app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {
return {
displayCalendar: function($scope) {
$http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
$scope.holidayList = data;
console.log($scope.holidayList);
}).error(function(data, status, headers, config) {
alert("error");
});
$calendar = $('[ui-calendar]');
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
$scope.changeView = function(view) {
$calendar.fullCalendar('changeView', view);
};
var m = null;
if ($scope.selectable == "Yes") {
m = true;
} else {
m = false;
}
/* config object */
$scope.uiConfig = {
calendar: {
lang: 'da',
height: 400,
editable: true,
selectable: m,
header: {
left: 'month basicWeek basicDay',
center: 'title',
right: 'today prev,next'
},
eventClick: function(date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
alert("clicked" + date.title);
},
select: function(start, end, allDay) {
var obj = {};
obj.startDate = start.toDate();
obj.endDate=moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');
$rootScope.selectionDate = obj;
$("#modal1").openModal();
// calendar.fullCalendar('unselect');
},
dayRender: function (date, cell) {
var today = new Date();
today=moment(today).toDate();
var end = new Date();
end=moment(end).toDate();
end.setDate(today.getDate()+7);
date=moment(date).toDate();
angular.forEach($scope.holidayList,function(value){
if(((moment(value.holiday_date).format("YYYY-MM-DD"))==moment(date).format("YYYY-MM-DD")))
{
cell.css("background-color", "red");
}
});
},
eventRender: $scope.eventRender,
}
};
$scope.events = [];
$scope.eventSources = [$scope.events];
$http.get($scope.url, {
cache: true,
params: {}
}).then(function(data) {
console.log(data);
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function(value) {
console.log(value.title);
if (value.approvalStatus == "Approved") {
var k = '#114727';
} else {
k = '#b20000'
}
$scope.events.push({
title: value.signum,
description: value.signum,
start: value.startDate,
end: value.endDate,
allDay: value.isHalfDay,
stick: true,
status: value.approvalStatus,
backgroundColor: k
});
});
});
}
}
}]);
Remember that the REST call is asynchronous. Just put all the code that set colours inside a promise, so when the REST service rest/leave/holidayList responses, then you paint the colours. You can use nested promises if needed.
Here's some code:
$http.get('rest/leave/holidayList').then(function(response) {
// success
$scope.holidayList = data;
/* config object */
$scope.uiConfig = {
calendar: {
/* calendar code */
}
}
}, function(response) {
// error handler
});
To compare the use of "success" and "then" have a look at:
https://stackoverflow.com/a/16385350/8058079

Add Right Click Event to Full calender Angular JS Api

I am using the Angular UI Calender API in my MVC Project
UI Calender API [http://angular-ui.github.io/ui-calendar/]
I want to add right click Context Menu to it.On clicking any date or Event the context Menu should appear containing link options
1.Add Appointment
2.Add Meeting
3.Add Task
I have used the Bootstrap Context Menu https://github.com/Templarian/ui.bootstrap.contextMenu
The Problem I am facing is on right click the context menu is appearing the event does not captures the Date and Event details from the Calender which i need to pass to show in a POP UP.
I have used below code in my Angular Js Controller.
var calendarDemoApp = angular.module('myCalendarApp', ['ui.calendar', 'ui.bootstrap', 'ui.bootstrap.contextMenu']);
calendarDemoApp.controller('CalendarCtrl',
function ($scope, $http,$compile, $timeout, uiCalendarConfig) {
$scope.SelectedEvent = null;
var isFirstTime = true;`enter code here`
$scope.events = [];
$scope.eventSources = [$scope.events];
//Load events from server
$http.get('/home/getevents', {
cache: true,
params: {}
}).then(function (data) {
$scope.events.slice(0, $scope.events.length);
angular.forEach(data.data, function (value) {
$scope.events.push({
title: value.Title,
description: value.Description,
start: new Date(parseInt(value.StartAt.substr(6))),
end: new Date(parseInt(value.EndAt.substr(6))),
allDay: value.IsFullDay,
stick: true
});
});
});
/* alert on eventClick */
$scope.alertOnEventClick = function (date, jsEvent, view) {
$scope.alertMessage = (date.title + ' was clicked ');
};
/* alert on Drop */
$scope.alertOnDrop = function (event, delta, revertFunc, jsEvent, ui, view) {
$scope.alertMessage = ('Event Dropped to make dayDelta ' + delta);
};
/* alert on Resize */
$scope.alertOnResize = function (event, delta, revertFunc, jsEvent, ui, view) {
$scope.alertMessage = ('Event Resized to make dayDelta ' + delta);
};
/* add and removes an event source of choice */
$scope.addRemoveEventSource = function (sources, source) {
var canAdd = 0;
angular.forEach(sources, function (value, key) {
if (sources[key] === source) {
sources.splice(key, 1);
canAdd = 1;
}
});
if (canAdd === 0) {
sources.push(source);
}
};
/* add custom event*/
$scope.addEvent = function () {
};
/* remove event */
$scope.remove = function (index) {
$scope.events.splice(index, 1);
};
/* Change View */
$scope.changeView = function (view, calendar) {
uiCalendarConfig.calendars[calendar].fullCalendar('changeView', view);
};
/* Change View */
$scope.renderCalendar = function (calendar) {
$timeout(function () {
if (uiCalendarConfig.calendars[calendar]) {
uiCalendarConfig.calendars[calendar].fullCalendar('render');
}
});
};
/*COntext Menu*/
var AppointmentHtml = '<div style="cursor: pointer;"><i class="glyphicon glyphicon-plus"></i>New Appointment</div>';
var AppointmentItem = {
html: AppointmentHtml, click: function ($itemScope, event, modelValue, text, $li, date, jsEvent, view) {
debugger;
var winH = $(window).height();
var winW = $(window).width();
$.ajax({
url: '/Home/Appointment',
data: {},
cache: false,
success: function (result) {
//alert(result);
$("#dialog-content").html(result);
$("#divEdit").dialog({
modal: true,
title: 'Add Appointment',
close: function (event, ui) {
$(this).dialog('destroy');
}
});
$(".ui-dialog").css({ 'min-width': '600px', 'left': winW / 2 - 300 });
},
error: function (request, status, error) {
alert(status);
}
});
}
};
var MeetingHtml = '<div style="cursor: pointer;"><i class="glyphicon glyphicon-user"></i>New Meeting</div>';
var MeetingItem = {
html: MeetingHtml, click: function ($itemScope, event, modelValue, text, $li) {
alert("New Appointment");
console.info($itemScope);
console.info(event);
console.info(modelValue);
console.info(text);
console.info($li);
}
};
var TaskHtml = '<div style="cursor: pointer;"><i class="glyphicon glyphicon-tasks"></i>New Task</div>';
var TaskItem = {
html: TaskHtml, click: function ($itemScope, event, modelValue, text, $li) {
alert("New Task");
console.info($itemScope);
console.info(event);
console.info(modelValue);
console.info(text);
console.info($li);
}
};
$scope.customHTMLOptions = [AppointmentItem, MeetingItem,
TaskItem
];
/* Render Tooltip */
$scope.eventRender = function (event, element, view) {
element.attr({
'tooltip': event.title,
'tooltip-append-to-body': true
});
$compile(element)($scope);
};
/* config object */
$scope.uiConfig = {
calendar: {
height: 450,
editable: true,
header: {
left: 'title',
center: '',
right: 'today prev,next'
},
eventClick: function (event) {
$scope.SelectedEvent = event;
},
eventDrop: $scope.alertOnDrop,
eventResize: $scope.alertOnResize,
eventRender: $scope.eventRender,
eventAfterAllRender: function () {
if ($scope.events.length > 0 && isFirstTime) {
//Focus first event
uiCalendarConfig.calendars.myCalendar.fullCalendar('gotoDate', $scope.events[0].start);
isFirstTime = false;
}
}
}
};
$scope.changeLang = function () {
if ($scope.changeTo === 'Hungarian') {
$scope.uiConfig.calendar.dayNames = ["Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat"];
$scope.uiConfig.calendar.dayNamesShort = ["Vas", "Hét", "Kedd", "Sze", "Csüt", "Pén", "Szo"];
$scope.changeTo = 'English';
} else {
$scope.uiConfig.calendar.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
$scope.uiConfig.calendar.dayNamesShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
$scope.changeTo = 'Hungarian';
}
};
/* event sources array*/
//$scope.eventSources = [$scope.events, $scope.eventSource, $scope.eventsF];
//$scope.eventSources2 = [$scope.calEventsExt, $scope.eventsF, $scope.events];
});
Below is my HTML Code:
<section id="directives-calendar" ng-controller="CalendarCtrl">
<div class="calendar" ng-model="eventSources" calendar="myCalendar" context-menu="customHTMLOptions" config="uiConfig.calendar" ui-calendar="uiConfig.calendar"></div>
</Section>

ng-infinite scroll angular setting offset

Need to keep track of my offset so that I can get the next set each time either scroll or click 'Load more'. It improves performance. I am trying out here by setting offset and limit and passing as request params to my node server,but how to update or increment after that limit using offset:
my url as: /foo?limit=7&&offset=0;
My angular controller function as:
$scope.findDetails = function(){
var limit = 10;
var offset = 0;
//DataService.getUsers(limit,offset).then(function(customerdetails){
DataService.getUsers({limit,offset},function(customerdetails){
$scope.customers = customerdetails;
}, function(error){
$scope.status = 'Unable to load customer data: ' + error.message;
});
};
You must keep the offset in the scope of the controller and update the offset every time the infinite directive request more records to display:
$scope.limit = 10;
$scope.offset = 0;
//bind this function to the ng-infinite directive
$scope.infiniteScrollFunction = function() {
$scope.offset += $scope.limit;
$scope.findDetails();
};
$scope.findDetails = function() {
DataService.getUsers({limit: $scope.limit,offset: $scope.offset},
function(customerdetails){
...
}
var $scope.height = $('#div-height').height()
var flag = false;
var $scope.customers = []
$(window).scroll(function() {
if ($(this).scrollTop() > $scope.height-2000) {
if (!flag) {
flag = true;
refreshCustomers();
}
}
});
function refreshCustomers() {
DataService.getCustomers().then(function (data) {
$scope.customers = $scope.customers.concat(data);
setTimeout(function () {
$scope.height = $('#div-height').height();
flag = false
}, 0.1);
});
}
In DataService
factory.getCustomers = function(){
return $http.get(...api......&&limit=7).then(function (results) {
var customers = results.data.customers;
return customers;
});
};
Now after the window is scrolled up to certain height(windowHeight-2000px), the api is called again to get data. The previous data is being concatenated with present data.

Firebase child_removed not working in real-time

I am following tutsplus Real time web apps with Angularjs and Firebase.
I have main.js (below) which allows me to add and change items in Firebase in real time with no refresh of the browser (in Chrome and Safari).
However when I delete a message from Firebase I have to refresh the browser for the message list to update - so not in real time. I can't see where the problem is.
/*global Firebase*/
'use strict';
/**
* #ngdoc function
* #name firebaseProjectApp.controller:MainCtrl
* #description
* # MainCtrl
* Controller of the firebaseProjectApp
*/
angular.module('firebaseProjectApp')
.controller('MainCtrl', function ($scope, $timeout) {
var rootRef = new Firebase('https://popping-inferno-9738.firebaseio.com/');
var messagesRef = rootRef.child('messages');
$scope.currentUser=null;
$scope.currentText=null;
$scope.messages=[];
messagesRef.on('child_added', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
console.log(snapshotVal);
$scope.messages.push({
text: snapshotVal.text,
user: snapshotVal.user,
name: snapshot.key()
});
});
});
messagesRef.on('child_changed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
function deleteMessageByName(name){
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
$scope.messages.splice(i, 1);
break;
}
}
}
function findMessageByName(name){
var messageFound = null;
for(var i=0; i < $scope.messages.length; i++){
var currentMessage = $scope.messages[i];
if(currentMessage.name === name){
messageFound = currentMessage;
break;
}
}
return messageFound;
}
$scope.sendMessage = function(){
var newMessage = {
user: $scope.currentUser,
text: $scope.currentText
};
messagesRef.push(newMessage);
};
});
The code that is invoked when a message is deleted from Firebase:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
var snapshotVal = snapshot.val();
var message = findMessageByName(snapshot.key());
message.text = snapshotVal.text;
});
});
This code never actually deletes the message from the HTML/DOM.
There is a convenient deleteMessageByName method to handle the deletion. So if you modify the above to this, it'll work:
messagesRef.on('child_removed', function(snapshot){
$timeout(function() {
deleteMessageByName(snapshot.key());
});
});

Resources