我有一个for循环将数据插入到我的表中,效果很好。
问题是每个循环我希望它开始一个新行,但它启动一个新表。任何想法如何解决这个问题?
'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 = "<a href='javascript:;' data-ng-click = " + deleteFunction + "><img src='assets/images/icons/close_icon.png'></a>";
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 = "<a href='javascript:;' data-ng-click = " + deleteFunction + "><img src='assets/images/icons/close_icon.png'></a>";
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);
});
答案 0 :(得分:1)
您应该将代码更改为在表体内循环,而不是在整个表代码中循环:
<div id="mobile-content">
<table class="table table-hover">
<thead>
<tr>
<th>Account Name</th>
<th>Balance</th>
<th>Start Date</th>
</tr>
</thead>
<tbody>
<?php if (isset($records)) : foreach ($records as $row) : ?>
<tr>
<td><?php echo $row->bank_name; ?></td>
<td><?php echo $row->bank_balance; ?></td>
<td><?php echo $row->bank_start_date; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
注意:我还删除了额外的<tr>
,因为这三个单元格需要一行。
我希望有帮助:D