AngularJS extend model - angularjs

I had in my old project this bit of code for an API:
.factory('Api', ['$resource', 'apiUrl', function ($resource, api) {
var Api = $resource(api + ':path', {
path: '#path'
});
return Api;
}])
and then I had an Order model which extended this factory class like this:
.factory('Order', ['$filter', 'Api', function ($filter, api) {
var Order = api;
angular.extend(Order.prototype, {
getDescription: function () {
var rolls = 0,
cuts = 0,
skus = [],
lines = $filter('orderBy')(this.lines, 'sku');
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
switch (line.type) {
case 0: // cut
cuts++;
break;
case 1: // roll
rolls++
break;
}
if (skus.indexOf(line.sku) == -1) {
skus.push(line.sku);
}
}
var description = '';
description += cuts > 0 ? cuts > 1 ? cuts + ' x cuts' : cuts + ' x cut' : '';
description += rolls > 0 && description.length > 0 ? ', ' : '';
description += rolls > 0 ? rolls > 1 ? rolls + ' x rolls' : rolls + ' x roll' : '';
description += skus.length == 1 ? ' of ' + skus[0] : '';
return description;
},
getStatus: function () {
var lines = this.lines,
status = lines[0].status;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (status !== line.status)
return 'Multiple';
}
return status;
},
getDeliveryDate: function () {
var lines = this.lines,
date = lines[0].dates.delivery;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (date !== line.dates.delivery)
return 'Multiple';
}
date = new Date(date);
return date;
},
getDispatchDate: function () {
var lines = this.lines,
date = lines[0].orderDate;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (date !== lines.orderDate)
return 'Multiple';
}
date = new Date(date);
return date;
}
});
return Order;
}]);
Now, I have recently changed my API factory to this:
// ---
// CONSTANTS.
// ---
.constant('apiUrl', 'http://localhost:54326/')
//.constant('apiUrl', 'http://localhost:81/')
// ---
// SERVICES.
// ---
.service('Api', ['$http', 'HttpHandler', 'apiUrl', function ($http, handler, apiUrl) {
// Private function to build our request
var buildRequest = function (url, method, data, params) {
var model = {
method: method,
url: apiUrl + url,
data: data,
params: params
};
return $http(model);
}
// GET
this.get = function (url, params) {
return handler.loadData(buildRequest(url, 'GET', null, params));
}
// POST
this.post = function (url, data) {
return handler.loadData(buildRequest(url, 'POST', data));
}
// PUT
this.put = function (url, data) {
return handler.loadData(buildRequest(url, 'PUT', data));
}
// DELETE
this.delete = function (url, data) {
return handler.loadData(buildRequest(url, 'DELETE', data));
}
}])
When I did this, my order model no longer works. I get an error stating:
Cannot read property '$$hashKey' of undefined
Is there a way I can get my Order model to use the new API factory? Specifically I want to attach functions each object returned by the API.

Related

How can maintain the view in the bottom of the list when I add another element in my infinitescroll list ? angularjs

I have an issue I have a "chat" and when I add a new text in my infinite scroll container,
I go back to the top of the page, i'm not stuck to the bottom.
How can I maintain the page in the bottom of my page while people chat
my service
tabs.factory('chat', function ($http, $timeout, $q) {
return {
default: {
delay: 100
},
data: [],
dataScroll: [],
init: function (data) {
if (this.data.length == 0) {
for (var i = 0; i < data.length; i++) {
this.data[i] = data[i]
}
} else {
var tailleDataSaved = this.data.length
var dataAAjouter = data.slice(tailleDataSaved)
for (var i = 0; i < dataAAjouter.length; i++) {
this.data.push(dataAAjouter[i])
}
}
},
request: function (showAll) {
var self = this;
var deferred = $q.defer();
var index = this.dataScroll.length
var ndDataVisible = 7
var start = index;
var end = index + ndDataVisible - 1;
$timeout(function () {
if (!showAll) {
var item = []
if (start < end) {
for (var i = start; i < end; i++) {
console.log(start)
console.log(end)
console.log(self.data[i])
if (item = self.data[i]) {
self.dataScroll.push(item);
}
}
}
} else {
self.dataScroll = self.data
}
deferred.resolve(self.dataScroll);
}, 0);
return deferred.promise;
}
}
})
my js file
$scope.listChat= function () {
$scope.isActionLoaded = false;
$http.get(apiurl).then(function (response) {
chat.init(response.data)
$scope.isActionLoaded = true
})
}
$scope.listChatInfiniteScroll = function () {
$scope.isScrollDataLoaded = false
ticketListeActionScroll.request(false).then(function (response) {
$scope.actionsInfiniteScroll = response
$scope.isScrollDataLoaded = true
})
}
html file
<div ng-if="isActionLoaded" infinite-scroll='listChatInfiniteScroll ()' infinite-scroll-distance='1'>
<div ng-repeat="chat in actionsInfiniteScroll">
{{chat.text}}
</div>
</div>
Each time I add a new message it calls listChat

How to return a promise from an AngularJS Service using $q.all

The goal is to return a boolean value defining if a Job can be posted based on Earned staffing.
There are different pieces that come from three different sql tables. Rather than making a sql query that returns all of them in one result, i'm trying to understand how to use the $q.all function. The problem is that I am not getting a promise back from the service. The error is: TypeError: Cannot read property 'then' of undefined
There a few articles on this subject but most that I have found are old and still refer to using defer. I have tried the suggestions in the others and none of them have worked. They mentioned that the $q.all needs a return, and to return the $q.resolve and $q.reject for the return values.
Here is the code in my service:
function isMDOLevelAllowed(mdoLevel, finance) {
this.crData = "";
this.pData = "";
var mdoLevelToMatch = "", mdoMatrix = "", mdoOnRollsTotal = 0, mdoAuthTotal = 0;
var mdoVarianceTotal = 0, mdoPending = 0, mdoPendingThisLevel = 0;
return $q.all([
getCRO36ByFinance(finance),
epEarnedMDOSDOResource(finance),
getPendingByFinance(finance)
]).then(function (data) {
var crData = data[0];
var eData = data[1];
var pData = data[2];
var mdoData = crData.filter(function (m) { return m.jobType === "MDO"; });
mdoLevelToMatch = mdoData.filter(function (m) { return m.payGrade === mdoLevel; })[0];
mdoVarianceTotal = mdoData.reduce(function (a, b) { return a + b.variance; }, 0);
mdoMatrix = mdoData.map(function (m) { return { payGrade: m.payGrade, authorized: m.totalAuthorized }; });
mdoPending = pData.mdoTotalCount;
mdoPendingThisLevel = eval("pData.mdO" + mdoLevelToMatch.payGrade + "Count");
// Check if over Total Authorized
if (mdoVarianceTotal + mdoPending < 0) {
// Check if over Paylevel Authorized
if (mdoLevelToMatch.variance + mdoPendingThisLevel < 0) {
return $q.resolve();
}
else {
return $q.reject();
}
}
else {
return $q.reject();
}
}).$promise;
}
var service = {
getEarnedByFinance: getEarnedByFinance,
getCRO36ByFinance: getCRO36ByFinance,
getPendingByFinance: getPendingByFinance,
isMDOLevelAllowed: isMDOLevelAllowed,
isSDOAllowed: isSDOAllowed
};
return service;
How about trying:
function isMDOLevelAllowed(mdoLevel, finance) {
var defer = $q.defer();
this.crData = "";
this.pData = "";
var mdoLevelToMatch = "", mdoMatrix = "", mdoOnRollsTotal = 0, mdoAuthTotal = 0;
var mdoVarianceTotal = 0, mdoPending = 0, mdoPendingThisLevel = 0;
$q.all([
getCRO36ByFinance(finance),
epEarnedMDOSDOResource(finance),
getPendingByFinance(finance)
]).then(function (data) {
var crData = data[0];
var eData = data[1];
var pData = data[2];
var mdoData = crData.filter(function (m) { return m.jobType === "MDO"; });
mdoLevelToMatch = mdoData.filter(function (m) { return m.payGrade === mdoLevel; })[0];
mdoVarianceTotal = mdoData.reduce(function (a, b) { return a + b.variance; }, 0);
mdoMatrix = mdoData.map(function (m) { return { payGrade: m.payGrade, authorized: m.totalAuthorized }; });
mdoPending = pData.mdoTotalCount;
mdoPendingThisLevel = eval("pData.mdO" + mdoLevelToMatch.payGrade + "Count");
// Check if over Total Authorized
if (mdoVarianceTotal + mdoPending < 0) {
// Check if over Paylevel Authorized
if (mdoLevelToMatch.variance + mdoPendingThisLevel < 0) {
defer.resolve();
}
else {
defer.reject();
}
}
else {
defer.reject();
}
});
return defer.promise;
}
Take a note on how i defined var defer = $q.defer(); and then returned defer.promise just once. You dont need to return resolve and reject
Thank you for your help. I got it to work. I changed the $q.resolve, $q.reject to a return true or false, and removed the $promise at the end.
function isMDOLevelAllowed(mdoLevel, finance) {
this.crData = "";
this.pData = "";
var mdoLevelToMatch = "", mdoMatrix = "", mdoOnRollsTotal = 0, mdoAuthTotal = 0;
var mdoVarianceTotal = 0, mdoPending = 0, mdoPendingThisLevel = 0;
return $q.all([
getCRO36ByFinance(finance),
epEarnedMDOSDOResource(finance),
getPendingByFinance(finance)
]).then(function (data) {
var crData = data[0];
var eData = data[1];
var pData = data[2];
var mdoData = crData.filter(function (m) { return m.jobType === "MDO"; });
mdoLevelToMatch = mdoData.filter(function (m) { return m.payGrade === mdoLevel; })[0];
//mdoOnRollsTotal = mdoData.reduce(function (a, b) { return a + b.totalOnRolls; }, 0);
//mdoAuthTotal = mdoData.reduce(function (a, b) { return a + b.totalAuthorized; }, 0);
mdoVarianceTotal = mdoData.reduce(function (a, b) { return a + b.variance; }, 0);
mdoMatrix = mdoData.map(function (m) { return { payGrade: m.payGrade, authorized: m.totalAuthorized }; });
mdoPending = pData.mdoTotalCount;
mdoPendingThisLevel = eval("pData.mdO" + mdoLevelToMatch.payGrade + "Count");
// Check if over Total Authorized
if (mdoVarianceTotal + mdoPending < 0) {
// Check if over Paylevel Authorized
if (mdoLevelToMatch.variance + mdoPendingThisLevel < 0) {
return true;
}
else {
return false;
}
}
else {
return false;
}
});
}

Cordova.writefile function doesn't run, but doesn't give an error

I'm making an ionic application. I have a function called scope.win() that's supposed to fire when a quiz is finished, and then update the JSON file to add that quiz to the number of finished quizzes but it doesn't run properly.It doesn't give off any error. The function just stops running at a certain point and the app keeps going and nothing is happening.
This is the controller's file
angular.module('controllers', ['services'])
.controller('MainCtrl', function ($scope, $state, data) {
$scope.$on('$ionicView.enter', function () {
data.create();
});
$scope.chapter = data.chapterProgress();
})
.controller("BtnClick", function ($scope, lives, data, $cordovaFile, $ionicScrollDelegate) {
var live = 3;
var clickedOn = [];
var numQuestions;
$scope.part2Cred = false;
$scope.part3Cred = false;
$scope.part4Cred = false;
$scope.part5Cred = false;
$scope.part6Cred = false;
$scope.part7Cred = false;
$scope.part8Cred = false;
$scope.part9Cred = false;
$scope.part10Cred = false;
$scope.partQCred = false;
$scope.setNumQuestions = function(num){
numQuestions = num;
}
$scope.updatelives = function (){
//grabs the element that is called liv then updates it
var livesOnPage = document.getElementById('liv');
livesOnPage.innerHTML = live;
}
$scope.wrong = function (event){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "grey";
clickedOn.push(selec);
live = live - 1;
if(live == 0){
$scope.gameover();
}
else{
$scope.updatelives();
}
}
}
$scope.right = function (event,chapter, section){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "green";
clickedOn.push(selec);
numQuestions = numQuestions - 1;
if(numQuestions === 0){
$scope.win(chapter, section);
}
}
}
$scope.gameover = function(){
alert("game over please try again");
live = 3;
$ionicScrollDelegate.scrollTop();
$scope.partQCred = false;
$scope.part1Cred = !$scope.part1Cred;
for(i = 0; i< clickedOn.length;i++){
clickedOn[i].style.color = "rgb(68,68,68)";
}
}
$scope.win = function (chapter, section) {
alert("Well Done");
var data = data.chapterProgress(); // It is at this point that the //function stops running without giving off any error.
alert("Good Job");
var sectionsComplete = data[chapter].sectionsCompleted;
var totalsection = data[chapter].totalSections;
if (section === totalSection) {
window.location.href = "#/chapter1sections";
return;
}
if (section > sectionsComplete) {
data[chapter].sectionsCompleted += 1;
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
document.addEventListener('deviceready', function () {
$cordovaFile.writeFile(url + "js/", "chapters.json", data, true)
.then(function (success) {
// success
alert("Json file updated")
window.location.href = "#/chapter1sections";
}, function (error) {
// error
});
});
}
}
});
Here is the Services file. It seems to run fine but it is referenced a lot in the problematic sections of code in the controllers so I figured it was necessary to put it here.
angular.module('services', [])
.service('lives', function () {
var live = 3;
return {
getlives: function () {
return live;
},
setlives: function (value) {
live = value;
}
};
})
.service('data', function ($cordovaFile, $http) {
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
return {
//Run this function on startup to check if the chapters.json file exists, if not, then it will be created
create: function () {
var init = {
"one": {
"sectionsCompleted": 0,
"totalSections": 4
},
"two": {
"sectionsCompleted": 0,
"totalSections": 1
}
};
$cordovaFile.writeFile(url + "js/", "chapters.json", init, false)
.then(function (success) {
// success
}, function (error) {
// error
});
},
chapterProgress: function () {
return $http.get(url + "js/chapters.json").success(function (response) {
var json = JSON.parse(response);
return json;
}, function (error) {
alert(error);
});
}
}
});
Thank You so much for the help and time.

TypeError: 'undefined' is not an object (evaluating 'authDetails.access_token') while i

I am getting the following error in my controller:
angular.module('bcpBackOffice').controller('assetsCtrl', ['$scope', '$state', '$log', '$filter', '$compile', 'ApplicationConfig', '$mdDialog', 'RoomManagerFactory',
The error is showing for the variable authDetails.access_token in my controller.
Here is my controller
'use strict';
/**
* #ngdoc function
* #name bcpBackOffice.controller:assetsCtrl
* #description
* # assetsCtrl
* Controller of the bcpBackOffice
*/
angular.module('bcpBackOffice').controller('assetsCtrl', ['$scope', '$state', '$log', '$filter', '$compile', 'ApplicationConfig', '$mdDialog', 'RoomManagerFactory',
'RoomService', 'DataService', 'RoomServicesVO', 'RoomPricingVO','BcpBase64ImageDataEncodedMultipartFileVO','ImagePath','RoomVO','ImageFileExtensionPattern', assetsCtrl]);
function assetsCtrl($scope, $state, $log, $filter, $compile, ApplicationConfig, $mdDialog, RoomManagerFactory, RoomService, DataService,
RoomServicesVO, RoomPricingVO, BcpBase64ImageDataEncodedMultipartFileVO, ImagePath, RoomVO, ImageFileExtensionPattern) {
// Variable definition
var authDetails = ApplicationConfig.loggedInUserData.authDetails;
var accessToken = authDetails.access_token;
$scope.selectedTabIndex = 0;
$scope.masterData = "";
$scope.roomAttributes = [];
$scope.roomServiceRateUnits = [];
$scope.roomServices = [];
$scope.dayHours = null;
$scope.propertyId = ApplicationConfig.loggedInUserData.propertyId;
$scope.rooms = [];
$scope.populateMasterAttributeData = [];
$scope.attributeValue = [];
$scope.assetServices = new RoomServicesVO();
$scope.editAssetServicesFlag = false;
$scope.editAssetServicesIndex = '';
$scope.imageRoomPicturesPath = ImagePath.RoomImagePicturePath;
$scope.imageFloorPlanPath = ImagePath.RoomImageFloorPlanPath;
$scope.validateUploadedFile = validateUploadedFile;
$scope.assetsFromDateContainer = {};
$scope.weekdaySlot = [];
var weekdayPricingVO = new RoomPricingVO();
weekdayPricingVO.slotType = 'WEEKDAY';
$scope.weekdaySlot.push(weekdayPricingVO);
$scope.weekendSlot = [];
var weekendPricingVO = new RoomPricingVO();
weekendPricingVO.slotType = 'WEEKEND';
$scope.weekendSlot.push(weekendPricingVO);
// Function definition
$scope.increaseCounter = increaseCounter;
$scope.decreaseCounter = decreaseCounter;
$scope.loadDataForAssets = loadDataForAssets;
$scope.addWeekdaySlot = addWeekdaySlot;
$scope.addWeekendSlot = addWeekendSlot;
$scope.deleteWeekdaySlot = deleteWeekdaySlot;
$scope.deleteWeekendSlot = deleteWeekendSlot;
$scope.addInclusiveServices = addInclusiveServices;
$scope.closePopup = closePopup;
$scope.saveInclusiveServices = saveInclusiveServices;
$scope.getAssetsMasterData = getAssetsMasterData;
$scope.switchToAssetsServiceTab = switchToAssetsServiceTab;
$scope.saveRoomData = saveRoomData;
$scope.getDayHours = getDayHours;
$scope.addAdditionalServicesToRoom = addAdditionalServicesToRoom;
$scope.populateAttributeData = populateAttributeData;
$scope.getAllAssetsOfProperty = getAllAssetsOfProperty;
$scope.setWorkingHoursToTime = setWorkingHoursToTime;
$scope.disabledToDate = disabledToDate;
$scope.validatePricingSlot = validatePricingSlot;
$scope.editAssetService = editAssetService;
$scope.deleteAssetService = deleteAssetService;
$scope.reloadAssetServiceVO = reloadAssetServiceVO;
$scope.uploadFloorPlan = uploadFloorPlan;
$scope.uploadRoomImage = uploadRoomImage;
$scope.imagesDataParser = imagesDataParser;
/**
* RoomVO Object Contains Data.
*/
$scope.roomVO = RoomManagerFactory.retrieveInstance();
$scope.roomServicesVO = new RoomServicesVO();
$scope.roomPricingVO = new RoomPricingVO();
/**
* Save Room Data.(create new Asset.)
*/
function saveRoomData() {
$scope.roomVO.availableFromDate = $filter('date')(new Date($scope.assetsFromDateContainer.availableFromDate), "yyyy-MM-dd HH:mm:ss");
$log.debug($scope.roomVO);
if (typeof $scope.roomVO.roomType == "string" || $scope.roomVO.roomType instanceof String) {
$scope.roomVO.roomType = JSON.parse($scope.roomVO.roomType);
}
addWeekdayAndWeekendSlotToAsset();
RoomService.createRoomOfProperty($scope.roomVO, $scope.propertyId, accessToken).then(function (response) {
$scope.rooms.push(response.data);
$scope.roomVO = new RoomVO();
$state.go('template.' + ApplicationConfig.urlBasedOnUserRole + '.assets.show-assets');
},function(error){
$log.error(error);
});
}
/**
* Add Additional Services to Room.
*/
function addAdditionalServicesToRoom() {
$scope.roomServicesVO = $scope.assetServices;
if($scope.editAssetServicesFlag == true){
$scope.roomVO.editRoomServices($scope.editAssetServicesIndex,$scope.roomServicesVO);
}
else {
$scope.roomVO.addRoomServices($scope.roomServicesVO);
}
$scope.editAssetServicesFlag = false;
$scope.assetServices = new RoomServicesVO();
return true;
}
function getDayHours() {
DataService.getDayHoursFromJson().then(function (response) {
$scope.dayHours = response.data;
});
}
function setWorkingHoursToTime(fromTime) {
angular.forEach($scope.dayHours, function (dayHour, index) {
if (fromTime == dayHour.value) {
$scope.totimeIndex = index;
}
});
}
function reloadAssetServiceVO(){
$scope.editAssetServicesFlag = false;
$scope.assetServices = new RoomServicesVO();
}
function editAssetService(index){
$scope.editAssetServicesFlag = true;
$scope.editAssetServicesIndex = index;
$scope.roomServicesVO = $scope.roomVO.roomServices[index];
angular.copy($scope.roomServicesVO, $scope.assetServices);
}
function deleteAssetService(index){
$scope.roomVO.roomServices.splice(index,1);
}
function disabledToDate(fromTime, index, dayType) {
var selectOptions;
if (dayType == 'weekday') {
selectOptions = document.getElementsByClassName('toTimeSelectWeekday_' + index)[0].options;
}
if (dayType == 'weekend') {
selectOptions = document.getElementsByClassName('toTimeSelectWeekend_' + index)[0].options;
}
if (selectOptions.length > 0) {
angular.forEach(selectOptions, function (selectOption) {
selectOption.removeAttribute('disabled');
var value = $filter('date')(selectOption.value, 'HH:mm:ss');
var fromTimeFilter = $filter('date')(fromTime, 'HH:mm:ss');
console.log(value-fromTimeFilter);
if (value <= fromTimeFilter) {
selectOption.setAttribute('disabled', true);
}
});
}
}
/**
* get master data while adding new assets
*/
function getAssetsMasterData() {
switchToAssetsServiceTab(0);
var masterDataPromise = RoomService.getMasterDataOfRoom(accessToken);
masterDataPromise.then(function (promise) {
$scope.masterData = promise.data;
//$scope.roomAttributes = $scope.masterData.roomAttributes;
angular.copy($scope.masterData.roomAttributes, $scope.roomAttributes);
angular.copy($scope.masterData.roomServiceRateUnits, $scope.roomServiceRateUnits);
angular.copy($scope.masterData.roomServices, $scope.roomServices);
$scope.attributeValue = [];
populateAttributeData();
$log.debug($scope.masterData.roomAttributes);
$state.go('template.' + ApplicationConfig.urlBasedOnUserRole + '.assets.add-asset');
});
}
function getAllAssetsOfProperty() {
RoomService.getAllRoomsOfProperty(accessToken, $scope.propertyId).then(function (response) {
$scope.rooms = response.data;
});
}
function populateAttributeData() {
$scope.populateMasterAttributeData = [];
angular.forEach($scope.roomAttributes, function (attributeObject) {
if (typeof attributeObject.value == "string" || attributeObject.value instanceof String) {
var parsedAttributeValue = JSON.parse(attributeObject.value);
} else {
var parsedAttributeValue = attributeObject.value;
}
angular.forEach(parsedAttributeValue, function (attribute) {
var tempAttributeObject = {};
tempAttributeObject.id = attributeObject.id;
tempAttributeObject.label = attribute;
tempAttributeObject.checked = false;
$scope.populateMasterAttributeData.push(tempAttributeObject);
});
}, $scope.populateMasterAttributeData);
}
/**
* load the data after loading the page for Assets Page
*/
function loadDataForAssets() {
$scope.assetsFromDateContainer.availableFromDate = $filter('date')(new Date(), "yyyy-MM-dd HH:mm:ss");
$scope.roomVO.guestCapacity = 1;
$scope.roomVO.minimumBookingHours = 1;
}
/**
* Increase counter value on click on item/element
* #param value
*/
function increaseCounter(value) {
var countEle = document.getElementById(value);
countEle.value = +countEle.value + 1;
if (value == "countFld") {
$scope.roomVO.guestCapacity = countEle.value;
} else {
if (value == "countFld2") {
$scope.roomVO.minimumBookingHours = countEle.value;
}
}
}
/**
* Decrease counter value on click on item/element
* #param value
*/
function decreaseCounter(value) {
var countEle = document.getElementById(value);
if (countEle.value > 1) {
countEle.value = countEle.value - 1;
if (value == "countFld") {
$scope.roomVO.guestCapacity = countEle.value;
} else {
if (value == "countFld2") {
$scope.roomVO.minimumBookingHours = countEle.value;
}
}
}
else {
}
}
/**
* add time slot for weekday
*/
function addWeekdaySlot() {
var roomPricingVO = new RoomPricingVO();
roomPricingVO.slotType = 'WEEKDAY';
$scope.weekdaySlot.push(roomPricingVO);
var currentIndex = ($scope.weekdaySlot.length - 1);
var weekdaytbl = document.getElementById("weekdaySlotsTbl");
var lasti = weekdaytbl.rows.length;
var row = weekdaytbl.insertRow(lasti);
var cell1 = row.insertCell(0);
cell1.setAttribute("style", "width:80px;");
var cell2 = row.insertCell(1);
cell2.setAttribute("style", "width:80px;");
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
$log.debug($scope.weekdaySlot.length - 1);
var formTimeModel = "weekdaySlot[" + currentIndex + "].fromTime";
var toTimeModel = "weekdaySlot[" + currentIndex + "].toTime";
var rateModel = "weekdaySlot[" + currentIndex + "].rate";
cell1.innerHTML = document.getElementById("weekdays_fromTime").innerHTML;
cell1.getElementsByTagName("select")[0].setAttribute("ng-model", formTimeModel);
var disabledToDateFunction = 'disabledToDate(weekdaySlot[' + currentIndex + '].fromTime,' + currentIndex + ',\'weekday\')';
cell1.getElementsByTagName("select")[0].setAttribute("ng-change", disabledToDateFunction);
cell2.innerHTML = document.getElementById("weekdays_toTime").innerHTML;
cell2.getElementsByTagName("select")[0].setAttribute("ng-model", toTimeModel);
cell2.getElementsByTagName("select")[0].setAttribute("class", cell2.getElementsByTagName("select")[0].getAttribute("class") + ' toTimeSelectWeekday_' + currentIndex);
cell3.innerHTML = document.getElementById("weekdays_price").innerHTML;
cell3.getElementsByTagName("input")[0].setAttribute("ng-model", rateModel);
var deleteFunction = 'deleteWeekdaySlot($event,' + currentIndex + ')';
cell4.innerHTML = "<img src='assets/images/icons/close_icon.png'>";
disabledToDate($scope.weekdaySlot[currentIndex].fromTime, currentIndex,'weekday');
$compile($(row).contents())($scope);
}
/**
* add time slot for weekend
*/
function addWeekendSlot() {
var roomPricingVO = new RoomPricingVO();
roomPricingVO.slotType = 'WEEKEND';
$scope.weekendSlot.push(roomPricingVO);
var currentIndex = ($scope.weekendSlot.length - 1);
var weekdaytbl = document.getElementById("weekendSlotsTbl");
var lasti = weekdaytbl.rows.length;
var row = weekdaytbl.insertRow(lasti);
var cell1 = row.insertCell(0);
cell1.setAttribute("style", "width:80px;");
var cell2 = row.insertCell(1);
cell2.setAttribute("style", "width:80px;");
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var formTimeModel = "weekendSlot[" + currentIndex + "].fromTime";
var toTimeModel = "weekendSlot[" + currentIndex + "].toTime";
var rateModel = "weekendSlot[" + currentIndex + "].rate";
cell1.innerHTML = document.getElementById("weekdays_fromTime").innerHTML;
cell1.getElementsByTagName("select")[0].setAttribute("ng-model", formTimeModel);
var disabledToDateFunction = 'disabledToDate(weekendSlot[' + currentIndex + '].fromTime,' + currentIndex + ',\'weekend\')';
cell1.getElementsByTagName("select")[0].setAttribute("ng-change", disabledToDateFunction);
cell2.innerHTML = document.getElementById("weekdays_toTime").innerHTML;
cell2.getElementsByTagName("select")[0].setAttribute("ng-model", toTimeModel);
cell2.getElementsByTagName("select")[0].setAttribute("class", cell2.getElementsByTagName("select")[0].getAttribute("class") + ' toTimeSelectWeekend_' + currentIndex);
cell3.innerHTML = document.getElementById("weekdays_price").innerHTML;
cell3.getElementsByTagName("input")[0].setAttribute("ng-model", rateModel);
var deleteFunction = 'deleteWeekendSlot($event,' + currentIndex + ')';
cell4.innerHTML = "<img src='assets/images/icons/close_icon.png'>";
disabledToDate($scope.weekendSlot[currentIndex].fromTime, currentIndex, 'weekend');
$compile($(row).contents())($scope);
}
function addWeekdayAndWeekendSlotToAsset() {
var mergedWeekdayWeekendPricing = [];
mergedWeekdayWeekendPricing = $scope.weekdaySlot.concat($scope.weekendSlot);
$scope.roomVO.roomPricings = mergedWeekdayWeekendPricing;
}
/**
* delete weekday slots
* #param $event
*/
function deleteWeekdaySlot($event, currentIndex) {
var index = $event.currentTarget.parentNode.parentNode.rowIndex;
document.getElementById("weekdaySlotsTbl").deleteRow(index);
delete($scope.weekdaySlot[currentIndex]);
}
/**
* delete weekend slots
* #param $event
*/
function deleteWeekendSlot($event, currentIndex) {
var index = $event.currentTarget.parentNode.parentNode.rowIndex;
document.getElementById("weekendSlotsTbl").deleteRow(index);
delete($scope.weekendSlot[currentIndex]);
}
/**
* add Inclusive Services for Assets popup
*/
function addInclusiveServices() {
$mdDialog.show({
templateUrl: 'app/templates/views/' + ApplicationConfig.urlBasedOnUserRole + '/fragments/add-inclusive-assets-services.html',
scope: $scope,
preserveScope: true,
overlay: true,
clickOutsideToClose: false,
parent:angular.element('#addInclusiveServices')
});
}
/**
* Save added inclusive services for Assets
*/
function saveInclusiveServices() {
addAttributeToAsset();
$mdDialog.hide();
}
function addAttributeToAsset() {
$scope.attributeValue = [];
$scope.roomVO.roomAttributes = $scope.masterData.roomAttributes;
$log.debug($scope.populateMasterAttributeData);
if (typeof $scope.roomVO.roomAttributes == "string" || $scope.roomVO.roomAttributes instanceof String) {
$scope.roomVO.roomAttributes = JSON.parse($scope.roomVO.roomAttributes);
}
if ($scope.roomVO.roomAttributes.length != 0) {
angular.forEach($scope.roomVO.roomAttributes, function (roomAttribute) {
var filteredSelectedAttr = $filter('filter')($scope.populateMasterAttributeData, function (populateMasterAttributeData) {
return ((roomAttribute.id == populateMasterAttributeData.id)&&(populateMasterAttributeData.checked == true));
});
var tempAttributeValueArray = [];
angular.forEach(filteredSelectedAttr, function (filteredAttributeLabel) {
tempAttributeValueArray.push(filteredAttributeLabel.label);
$scope.attributeValue.push(filteredAttributeLabel.label);
});
roomAttribute.value = tempAttributeValueArray;
});
}
$scope.roomVO.roomAttributes = JSON.stringify($scope.roomVO.roomAttributes);
}
/**
* close the popup window
*/
function closePopup() {
$mdDialog.hide();
}
/**
* after adding new asset switch to next tab
* to add assets service
* #param index
*/
function switchToAssetsServiceTab(index) {
$scope.selectedTabIndex = index;
}
function validatePricingSlot(){
createDummyTimeSlots();
//var sortByStartTime = $filter('orderBy')($scope.weekdaySlot, expression, comparator);
return false;
}
function createDummyTimeSlots(){
var listOfHours = $filter('getValueArrayOfKey')($scope.dayHours)('value');
var operableHours = $filter('filter')(listOfHours, function(hour){
return (hour >= $scope.roomVO.operableHoursStartTime && hour <= $scope.roomVO.operableHoursEndTime);
});
var sortedByFromTimeAndToTime = $filter('orderBy')($scope.weekdaySlot, ['fromTime', 'toTime']);
angular.forEach(sortedByFromTimeAndToTime, function(sortedObject){
angular.forEach(operableHours, function(hour, index){
if(hour >= sortedObject.fromTime && hour <= sortedObject.toTime){
operableHours.splice(index, 1);
}
});
});
console.log("+++++++++++++++++operableHours++++++++++++++++++++");
console.log(operableHours);
}
function uploadFloorPlan(files) {
if(validateUploadedFile()) {
var roomFloorPlanVO = new BcpBase64ImageDataEncodedMultipartFileVO().getRoomFloorPlanVO();
roomFloorPlanVO.originalFileName = files[0].name;
roomFloorPlanVO.size = files[0].size;
roomFloorPlanVO.contentType = files[0].type;
if (files && files[0]) {
setImageBase64ToBase64VO(roomFloorPlanVO, files[0]);
}
$scope.roomVO.floorPlanImageData = roomFloorPlanVO;
$log.debug($scope.roomVO);
}
}
function uploadRoomImage(files) {
if (validateUploadedFile()) {
console.log(files);
angular.forEach(files, function (file) {
var roomImageVO = new BcpBase64ImageDataEncodedMultipartFileVO().getRoomImageVO();
roomImageVO.originalFileName = file.name;
roomImageVO.size = file.size;
roomImageVO.contentType = file.type;
if (files && files[0]) {
setImageBase64ToBase64VO(roomImageVO, file);
}
$scope.roomVO.addRoomImageData(roomImageVO);
});
$log.debug($scope.roomVO);
}
}
function setImageBase64ToBase64VO(roomFloorPlanAndImageDataVO, file) {
var FR = new FileReader();
FR.onload = function (e) {
roomFloorPlanAndImageDataVO.base64EncodedImageData = e.target.result;
};
FR.readAsDataURL(file);
}
function imagesDataParser(roomImages, index){
if (typeof roomImages == "string" || roomImages instanceof String) {
$scope.rooms[index].images = JSON.parse(roomImages);
}
}
function validateUploadedFile() {
var allowedFiles = [".jpg", ".jpeg", ".gif", ".png"];
var fileUpload = document.getElementById("myfile");
var myPicture = document.getElementById("myPicture");
var lblError = document.getElementById("lblError");
var errorMyPicture = document.getElementById("errorMyPicture");
if (fileUpload.files.length > 0) {
if (!(ImageFileExtensionPattern).test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
}
if (myPicture.files.length > 0) {
var flag = false;
for(var readFile = 0; readFile < myPicture.files.length;readFile ++) {
if (!(ImageFileExtensionPattern).test(myPicture.files[readFile].name.toLowerCase())) {
errorMyPicture.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
flag = true;
break;
}
}
if(flag){return false;}
if (myPicture.files.length > 5) {
errorMyPicture.innerHTML = "Oops!! You can upload max 5 files";
return false;
}
}
lblError.innerHTML = "";
errorMyPicture.innerHTML = "";
return true;
}
// called function on load
$scope.getDayHours();
$scope.getAllAssetsOfProperty();
}
**Here is my test case :**
'use strict';
describe('Controller: assetsCtrl', function () {
beforeEach(module('bcpBackOffice'));
beforeEach(module('BcpUIServices'));
beforeEach(module('ui.router'));
var assetsCtrl,
state,
log,
filter,
compile,
ApplicationConfig,
mdDialog,
RoomManagerFactory,
RoomService,
DataService,
RoomServicesVO,
RoomPricingVO,
$rootScope,
scope,
$httpBackend;
//Mock Data
var mockDayHours= [{
"label": "06:00 AM",
"value": "06:00:00"
},
{
"label": "07:00 AM",
"value": "07:00:00"
}];
beforeEach(inject(function(_$rootScope_, $controller, _$state_, _$log_, _$filter_, _$compile_, _ApplicationConfig_, _$mdDialog_, _RoomManagerFactory_, _RoomService_, _DataService_,
_RoomServicesVO_, _RoomPricingVO_, _$httpBackend_){
$rootScope = _$rootScope_;
scope = $rootScope.$new();
state = _$state_;
log = _$log_;
filter = _$filter_;
compile = _$compile_;
ApplicationConfig = _ApplicationConfig_;
mdDialog = _$mdDialog_;
RoomManagerFactory = _RoomManagerFactory_;
RoomService = _RoomService_;
DataService = _DataService_;
RoomServicesVO = _RoomServicesVO_;
RoomPricingVO = _RoomPricingVO_;
$httpBackend = _$httpBackend_;
assetsCtrl = $controller('assetsCtrl', {
$scope:scope,
$state:state,
$log:log,
$filter:filter,
$compile:compile,
ApplicationConfig:ApplicationConfig,
$mdDialog:mdDialog,
RoomManagerFactory:RoomManagerFactory,
RoomService:RoomService,
DataService:DataService,
RoomServicesVO:RoomServicesVO,
RoomPricingVO:RoomPricingVO
});
}));
beforeEach(function(){
ApplicationConfig.loggedInUserData.authDetails = {
access_token: "0e45e276-89ff-403f-8e02-7f85a41c2d26",
token_type: "bearer",
refresh_token: "ce872f46-5877-4266-9a0e-5199b63ac247",
expires_in: 10430,
scope: "read write"
};
$httpBackend.whenGET("app/mock_data/dayHours.json").respond(mockDayHours);
});
beforeEach(function(){
$rootScope.$digest();
});
it('should get day hours', function(){
scope.getDayHours();
$httpBackend.flush();
expect(scope.dayHours).toBe(mockDayHours);
});

Angularjs paging limit data load

I always manage pagination with angular
retrieve all the data from the server
and cache it client side (simply put it in a service)
now I have to cope with quite lot of data
ie 10000/100000.
I'm wondering if can get into trouble
using the same method.
Imo passing parameter to server like
page search it's very annoying for a good
user experience.
UPDATE (for the point in the comment)
So a possible way to go
could be get from the server
like 1000 items at once if the user go too close
to the offset (ie it's on the 800 items)
retrieve the next 1000 items from the server
merge cache and so on
it's quite strange not even ng-grid manage pagination
sending parameters to the server
UPDATE
I ended up like:
(function(window, angular, undefined) {
'use strict';
angular.module('my.modal.stream',[])
.provider('Stream', function() {
var apiBaseUrl = null;
this.setBaseUrl = function(url) {
apiBaseUrl = url;
};
this.$get = function($http,$q) {
return {
get: function(id) {
if(apiBaseUrl===null){
throw new Error('You should set a base api url');
}
if(typeof id !== 'number'){
throw new Error('Only integer is allowed');
}
if(id < 1){
throw new Error('Only integer greater than 1 is allowed');
}
var url = apiBaseUrl + '/' + id;
var deferred = $q.defer();
$http.get(url)
.success(function (response) {
deferred.resolve(response);
})
.error(function(data, status, headers, config) {
deferred.reject([]);
});
return deferred.promise;
}
};
};
});
})(window, angular);
(function(window, angular, undefined) {
'use strict';
angular.module('my.mod.pagination',['my.mod.stream'])
.factory('Paginator', function(Stream) {
return function(pageSize) {
var cache =[];
var staticCache =[];
var hasNext = false;
var currentOffset= 0;
var numOfItemsXpage = pageSize;
var numOfItems = 0;
var totPages = 0;
var currentPage = 1;
var end = 0;
var start = 0;
var chunk = 0;
var currentChunk = 1;
var offSetLimit = 0;
var load = function() {
Stream.get(currentChunk).then(function(response){
staticCache = _.union(staticCache,response.data);
cache = _.union(cache,response.data);
chunk = response.chunk;
loadFromCache();
});
};
var loadFromCache= function() {
numOfItems = cache.length;
offSetLimit = (currentPage*numOfItemsXpage)+numOfItemsXpage;
if(offSetLimit > numOfItems){
currentChunk++;
load();
}
hasNext = numOfItems > numOfItemsXpage;
totPages = Math.ceil(numOfItems/numOfItemsXpage);
paginator.items = cache.slice(currentOffset, numOfItemsXpage*currentPage);
start = totPages + 1;
end = totPages+1;
hasNext = numOfItems > (currentPage * numOfItemsXpage);
};
var paginator = {
items : [],
notFilterLabel: '',
hasNext: function() {
return hasNext;
},
hasPrevious: function() {
return currentOffset !== 0;
},
hasFirst: function() {
return currentPage !== 1;
},
hasLast: function() {
return totPages > 2 && currentPage!==totPages;
},
next: function() {
if (this.hasNext()) {
currentPage++;
currentOffset += numOfItemsXpage;
loadFromCache();
}
},
previous: function() {
if(this.hasPrevious()) {
currentPage--;
currentOffset -= numOfItemsXpage;
loadFromCache();
}
},
toPageId:function(num){
currentPage=num;
currentOffset= (num-1) * numOfItemsXpage;
loadFromCache();
},
first:function(){
this.toPageId(1);
},
last:function(){
this.toPageId(totPages);
},
getNumOfItems : function(){
return numOfItems;
},
getCurrentPage: function() {
return currentPage;
},
getEnd: function() {
return end;
},
getStart: function() {
return start;
},
getTotPages: function() {
return totPages;
},
getNumOfItemsXpage:function(){
return numOfItemsXpage;
},
search:function(str){
if(str===this.notFilterLabel){
if(angular.equals(staticCache, cache)){
return;
}
cache = staticCache;
}
else{
cache = staticCache;
cache = _.filter(cache, function(item){ return item.type == str; });
}
currentPage = 1;
currentOffset= 0;
loadFromCache();
}
};
load();
return paginator;
}
});
})(window, angular);
server side with laravel (All the items are cached)
public function tag($page)
{
$service = new ApiTagService(new ApiTagModel());
$items = $service->all();
$numOfItems = count($items);
if($numOfItems > 0){
$length = self::CHUNK;
if($length > $numOfItems){
$length = $numOfItems;
}
$numOfPages = ceil($numOfItems/$length);
if($page > $numOfPages){
$page = $numOfPages;
}
$offSet = ($page - 1) * $length;
$chunk = array_slice($items, $offSet, $length);
return Response::json(array(
'status'=>200,
'pages'=>$numOfPages,
'chunk'=>$length,
'data'=> $chunk
),200);
}
return Response::json(array(
'status'=>200,
'data'=> array()
),200);
}
The only trouble by now is managing filter
I've no idea how to treat filtering :(

Resources