how to add text in textarea cursor position by angularjs - angularjs

I want sample code to add a text to textarea angularjs code, can any one help.
Writing an SMS with some custom name field like {userName} #userName# etc. These are onclick events, when user clicks, respected text should be added in cursor position in textarea box.

Check this link and use the directive in your app
http://plnkr.co/edit/Xx1SHwQI2t6ji31COneO?p=preview
app.directive('myText', ['$rootScope', function($rootScope) {
return {
link: function(scope, element, attrs) {
$rootScope.$on('add', function(e, val) {
var domElement = element[0];
if (document.selection) {
domElement.focus();
var sel = document.selection.createRange();
sel.text = val;
domElement.focus();
} else if (domElement.selectionStart || domElement.selectionStart === 0) {
var startPos = domElement.selectionStart;
var endPos = domElement.selectionEnd;
var scrollTop = domElement.scrollTop;
domElement.value = domElement.value.substring(0, startPos) + val + domElement.value.substring(endPos, domElement.value.length);
domElement.focus();
domElement.selectionStart = startPos + val.length;
domElement.selectionEnd = startPos + val.length;
domElement.scrollTop = scrollTop;
} else {
domElement.value += val;
domElement.focus();
}
});
}
}
}])

Related

Resizable handles duplicate problem in undo redo functionality

" I am using resizable handles directive.I am creating undo / redo functionality then i am push html into array, When ever i am click on the undo button resizable Handles becoming duplicate."
I am pushing inside ng-repeat html into array where i am using resizable directive.
When ever i am going to append html(array for undo/redo) resizable handles become duplicate.
app.directive('rotateimage', function($compile) {
return {
restrict: 'A',
link: function postLink(scope, elem, attrs) {
elem.resizable({
handles: "ne, nw, se, sw,n,e,s,w",
aspectRatio: true
});
elem.on('resizestop', function(evt, ui) {
scope.id = [];
scope.style = [];
scope.html = [];
var id = elem.parent(".div01").attr('id');
scope.id.push(id);
scope.style.push($("#" + id).attr('style'));
$("#" + id).find(".ui-resizable-handle").remove();
scope.html.push($("#" + id).html().trim());
scope.historyApp.add(scope.style, scope.id, scope.html);
});
elem.on('resizestart', function(evt, ui) {
console.log("loll");
scope.id = [];
scope.style = [];
scope.html = [];
var id = elem.parent(".div01").attr('id');
scope.id.push(id);
scope.style.push($("#" + id).attr('style'));
$("#" + id).find(".ui-resizable-handle").remove();
scope.html.push($("#" + id).html().trim());
scope.historyApp.add(scope.style, scope.id, scope.html);
});
}
};
});
$scope.historyApp = {
stackStyle: [],
stackId: [],
html: [],
dataorignlbgcrop: [],
databbgval: [],
counter: -1,
add: function(style, id, html) {
++this.counter;
this.stackStyle[this.counter] = style;
this.stackId[this.counter] = id;
this.html[this.counter] = html;
this.doSomethingWith(style, id, html);
$scope.countBoxVal = true;
// delete anything forward of the counter
this.stackStyle.splice(this.counter + 1);
$scope.countBoxVal = true;
//alert(this.counter);
// alert($scope.countBoxVal);
},
undo: function() {
--this.counter;
// this.doSomethingWith(this.stackStyle[this.counter],this.stackId[this.counter]);
this.doSomethingWith(this.stackStyle[this.counter], this.stackId[this.counter], this.html[this.counter]);
--this.counter;
$scope.countBoxVal = false;
},
redo: function() {
++this.counter;
++this.counter;
this.doSomethingWith(this.stackStyle[this.counter], this.stackId[this.counter], this.html[this.counter]);
},
doSomethingWith: function(style, id, html) {
if (this.counter <= 0) {
this.counter = 0;
$scope.couterStackEnter = "enter";
//$scope.couterStackExit="undefined";
$('#undo').addClass('disabled');
$('#redo').removeClass('disabled');
} else {
$('#undo').removeClass('disabled');
}
var mathPro = Math.abs(this.counter);
var kp = mathPro + 1;
if (Math.abs(this.counter) >= this.stackStyle.length) {
$('#redo').addClass('disabled');
$scope.couterStackExit = "exit";
} else {
$('#redo').removeClass('disabled');
}
angular.forEach(html, function(val, key) {
console.log($scope.historyApp);
var myEl = angular.element(document.querySelector('#' + id[key]));
var ids = myEl.find(".forReverseUndoRedo").attr("id");
var myEls = angular.element(document.querySelector('#' + ids));
setTimeout(function() {
myEl.attr("style", style);
// myEls.clone().html("");
myEl.html("");
myEl.find(".ui-resizable-handle").remove();
myEl.append($compile(val)($scope));
$scope.$digest();
}, 100);
});
}
};

Why my function called multiple times after scanning the barcode through barcode scanner device in angularjs?

I am working on point of sale application here i am facing an issue when i am scanning barcode through barcode scanner device, my function called multiple times. For example when i am scanning barcode first time my function call one time, when i am scanning barcode without refreshing the page then function called two times,when i am scanning barcode third times then function called 4 times,that means function called multiple of 2. Here is my code which i have done, please check and rectify my issue.
// This is my barcode scanner function, in this function there are two api called 1 for getting whole invoice through barcode which length is more than or equal to 15 and 2 for after scanning barcode to get product.
$scope.returnProductByScanner = function (cod) {
if($location.path() == "/returnSale"){
if(cod != undefined){
var n = cod.length;
if(n == 15 || n > 15){
var action = {"barcode": cod};
var getDt = customerService.viewInvoiceOnBarcode(action);
getDt.then(function(data){
if(data.status == "success"){
var so = data.SO;
so.return = "return";
var sop = data.SOProducts;
$scope.addParkedProductIntoBag(sop,so);
}else{
var msg = data.error;
$scope.responseMsg(msg,"Failed");
}
})
}else{
// if($scope.newBagListOfProduct.length > 0){
var action = {"barcode":cod,"userid":uid,"org_id":org_id};
var getDt = customerService.getBarcodeScannedData(action);
getDt.then(function(data){
if(data.status == "success"){
var prodData = data.product;
$scope.addProductInBagSaleReturn(prodData);
}else{
var msg = data.msg;
$scope.responseMsg(msg,"Failed");
}
})
// }else{
// var msg = "Please first add invoice for return!";
// $scope.responseMsg(msg,"Failed");
// }
}
}
//$('input[name="myInput"]').focus();
}else{
cod = undefined;
}
$('input[name="myInput"]').focus();
};
// This is my HTML code
<div>
<div data-barcode-scanner="returnProductByScanner"></div>
<div><input name="myInput" type="text"
data-ng-model="testvalueret"
id="t" autofocus/>
</div>
</div>
// This is the derective what i have used.
.directive('barcodeScanner', function() {
return {
restrict: 'A',
scope: {
callback: '=barcodeScanner',
},
link: function postLink(scope, iElement, iAttrs){
// Settings
var zeroCode = 48;
var nineCode = 57;
var enterCode = 13;
var minLength = 3;
var delay = 300; // ms
// Variables
var pressed = false;
var chars = [];
var enterPressedLast = false;
// Timing
var startTime = undefined;
var endTime = undefined;
jQuery(document).keypress(function(e) {
if (chars.length === 0) {
startTime = new Date().getTime();
} else {
endTime = new Date().getTime();
}
// Register characters and enter key
if (e.which >= zeroCode && e.which <= nineCode) {
chars.push(String.fromCharCode(e.which));
}
enterPressedLast = (e.which === enterCode);
if (pressed == false) {
setTimeout(function(){
if (chars.length >= minLength && enterPressedLast) {
var barcode = chars.join('');
//console.log('barcode : ' + barcode + ', scan time (ms): ' + (endTime - startTime));
if (angular.isFunction(scope.callback)) {
scope.$apply(function() {
scope.callback(barcode);
alert(barcode);
});
}
}
chars = [];
pressed = false;
},delay);
}
pressed = true;
});
}
};
})
Directives that add event handlers to external elements need to remove those event handlers when the scope is destroyed:
app.directive('barcodeScanner', function() {
return {
restrict: 'A',
scope: {
callback: '=barcodeScanner',
},
link: function postLink(scope, iElement, iAttrs){
jQuery(document).on("keypress", keypressHandler);
scope.$on("$destroy", function () {
jQuery(document).off("keypress", keypressHandler);
});
function keypressHandler(e) {
if (chars.length === 0) {
startTime = new Date().getTime();
} else {
endTime = new Date().getTime();
}
//...
}
}
}
})
The AngularJS framework builds and destroys elements in the course of its operation. When those elements are destroyed, their respective scope is also destroyed and any necessary cleanup should be performed.

How to hide the $anchorScroll in the browser in AngularJS?

I am fairly new to AngularJS and I am using $anchorScroll to scroll to a particular section of the page after the results are rendered (which works fine).
However, I would like to hide the anchor that appears in the browser (refer to the image below). How can I achieve that?
Here's the section in the controller where I am using $anchorScroll and where I display the results after the user hits submits. Any help would appreciated:
$scope.SearchProvider = function(searchParam) {
try{
$scope.searchMode = 1;
var queryString='';
if($scope.formModel && $scope.formModel !== searchParam){
$scope.resultsCount = 0;
currentPage = 1;
}
if(searchParam){
$scope.formModel = searchParam;
for(var param in searchParam){
if(searchParam.hasOwnProperty(param)){
var paramValue = searchParam[param].value ? searchParam[param].value.trim() : searchParam[param].trim();
if (paramValue.length > 0)
queryString += param + '=' + paramValue + '&';
}
}
}
//debugger;
console.log(queryString);
queryString= '?' + queryString + 'currentpage=' + $scope.currentPage;
$http.get("/includes/ReturnProvidersList.cfm" + queryString)
.then(function(response){
$scope.providers = response.data.provider;
$scope.resultsCount = response.data.rowCount;
if (!$scope.providers){
$scope.NoResults = true;
$scope.ShowResults = false;
$scope.ShowDesc = false;
$location.hash('error');
// call $anchorScroll()
$anchorScroll('error');
}
else {
$scope.NoResults = false;
$scope.ShowResults = true;
$scope.ShowDesc = false;
$location.hash('ResultsAnchor');
// call $anchorScroll()
$anchorScroll('ResultsAnchor');
}
})
}
catch(err){ alert('No response.: ' + err.message); }
}

When to set caret position in $parser method of angularJS

I'm using ngModelController for formatting using input element. But I'm unable to set the caret position, if the user tries to enter any digit in the beginning or in the middle. As the caret alway jumps at the end.
What is the best place for calling set cursor?
ngModelController.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/ /g, '');
// $log.info(`viewValue = ${viewValue}`);
console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue}`);
console.log(`cursorPos = ${cursor.getCursorPos(elem[0])}`);
var newVal = ""
for (var i = 0; i < plainNumber.length; i++) {
if (i === 3 || i === 6) {
newVal += " ";
}
newVal += plainNumber[i];
}
cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);
// $log.info(`newVal = ${newVal}`);
elem.val(newVal);
return plainNumber;
});
similar question:
Preserving cursor position with angularjs
But I've added the below code, may be useful to other.
ngModelController.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/ /g, '');
// $log.info(`viewValue = ${viewValue}`);
console.log(`$modelValue = ${ngModelController.$modelValue} | $viewValue = ${ngModelController.$viewValue} | viewValue = ${viewValue} | cursorPos = ${cursor.getCursorPos(elem[0])} | oldVal = ${oldVal}`);
var newVal = ""
for (var i = 0; i < plainNumber.length; i++) {
if (i === 3 || i === 6) {
newVal += " ";
}
newVal += plainNumber[i];
}
if(newVal === viewValue) {
return viewValue;
}
// $log.info(`newVal = ${newVal}`);
var lastCursorPos = cursor.getCursorPos(elem[0]);
elem.val(newVal);
ngModelController.$setViewValue(newVal);
ngModelController.$render();
//cursor.setCursorPos(cursor.getCursorPos(elem[0]) + 1, elem[0]);
elem[0].setSelectionRange(lastCursorPos + 1, lastCursorPos + 1);
oldVal = newVal;
return plainNumber;
});

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);
});

Resources