I have a MVC view that has bootstrap navtabs in it. On each tab a different view loads. They are called delayed spiff, and instantspiff. I have added a datepicker and a button that should display data in the 2 views. The only problem is that when I click my button the views don't refresh. They keep their original data instead of the new data based on the date. I need to somehow reload the view after the date is selected and then show the new data. I'll share some of my code. Here's my code:
Main view:
<div class="container-fluid delayed_spiff_main">
<div class="row-fluid 1">
<div class="col-lg-12 delayed_spiff_body">
<div class="row spiff-datepicksection">
<div class="col-lg-6 pull-right">
<div class="col-sm-5 col-lg-offset-4">
<div class="form-group">
<div class="input-group date">
<input type="text" id="startDate" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="col-lg-3">
<input class="spiffdate-btn" type="button" value="Submit" />
</div>
</div>
</div>
<div class="row spiff_tabs_body">
<!-- Nav tabs -->
<ul class="nav nav-tabs spiff_tabs" role="tablist">
<li role="presentation" class="active">
Potential Spiff
</li>
<li role="presentation">
Instant Spiff
</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="delayedspiff"></div>
<div role="tabpanel" class="tab-pane" id="instantspiff"></div>
</div>
</div>
</div>
</div>
<script>
$(function () {
FormGet('dashboard/delayedspiff', 'delayedspiff');
});
</script>
javascript to load details in view:
function pullDetails(carrierId, startDate, status, divid) {
$.get("#Url.Action("getDelayedSpiffOrderDetails", "Dashboard")",
{ carrierId: carrierId, startDate: startDate, status: status },
function (data) {
$('.' + divid + ' .submitted_details').html(data);
$('.' + divid).removeClass('carrier-hide');
});
}
And just to make this even more confusing here is my Controller code:
public ActionResult DelayedSpiff(DateTime? startDate)
{
var available = _appService.GetFeatureStatus(1, "spiffDashboard");
if (!available)
return RedirectToAction("DatabaseDown", "Error", new { area = "" });
//var startDate = DateTime.Today.AddDays(-6);
if (!startDate.HasValue || startDate.Value == DateTime.MinValue)
{
startDate = DateTime.Today.AddDays(-7);
}
else
{
startDate = startDate.Value.AddDays(-7);
}
var acctId = User.AccountID;
var endDate = DateTime.Today.AddDays(1); // 1
Dictionary<DateTime, List<SpiffSummaryModel>> dict = new Dictionary<DateTime,List<SpiffSummaryModel>>();
try
{
var properties = new Dictionary<string, string>
{
{ "Type", "DelayedSpiff" }
};
telemetry.TrackEvent("Dashboard", properties);
dict = _reportingService.GetDailyDelayedSpiffSummaries(acctId, startDate.Value, endDate);
}
catch (Exception e)
{
if (e.InnerException is SqlException && e.InnerException.Message.StartsWith("Timeout expired"))
{
throw new TimeoutException("Database connection timeout");
}
var error = _errorCodeMethods.GetErrorModelByTcError(PROJID.ToString("000") + PROCID.ToString("00") + "001", "Exception Getting DelayedSpiff Dashboard View", PROJID, PROCID);
error.ErrorTrace = e.ToString();
_errorLogMethods.LogError(error);
return RedirectToAction("index", "error", new { error = error.MaskMessage });
}
var spiffDateModels = new List<DelayedSpiffDateModel>();
foreach (var entry in dict)
{
var spiffDateModel = new DelayedSpiffDateModel();
spiffDateModel.Date = entry.Key;
spiffDateModel.Carriers = new List<DelayedSpiffCarrierModel>();
foreach (var item in entry.Value)
{
var spiffCarrierModel = new DelayedSpiffCarrierModel();
spiffCarrierModel.Carrier = item.CarrierName;
spiffCarrierModel.CarrierId = item.CarrierId;
spiffCarrierModel.ApprovedSpiffTotal = item.ApprovedSpiffTotal;
spiffCarrierModel.EligibleActivationCount = item.EligibleActivationCount;
spiffCarrierModel.IneligibleActivationCount = item.IneligibleActivationCount;
spiffCarrierModel.PotentialSpiffTotal = item.PotentialSpiffTotal;
spiffCarrierModel.SubmittedActivationCount = item.SubmittedActivationCount;
spiffCarrierModel.UnpaidSpiffTotal = item.UnpaidSpiffTotal;
spiffDateModel.Carriers.Add(spiffCarrierModel);
}
spiffDateModels.Add(spiffDateModel);
}
spiffDateModels = spiffDateModels.OrderByDescending(x => x.Date).ToList();
return PartialView(spiffDateModels);
}
UPDATE code that loads inside of tabpanel:
<div class="container-fluid">
<div class="row">
<div class="col-lg-11 col-center-block delayspiffdata" id="details">
<table class="delay_spiff_tbl">
<thead>
<tr>
<th class="blank"></th>
<th>Submitted Activations / Potential Spiff</th>
<th>Approved Activations / Approved Spiff</th>
<th>Ineligible Activations / Unpaid Spiff</th>
</tr>
</thead>
<tbody>
#for (int date = 0; date < Model.Count; date ++)
{
<tr class="date-row" onclick="$('.date_#date').toggleClass('date-hide');">
<td class="spiffdate">
#Model[date].Date.ToString("dddd MM/dd/yyyy")
<i class="fa fa-plus-circle expander_open" ></i>
</td>
<td>#Model[date].Carriers.Sum(c => c.SubmittedActivationCount) / #Model[date].Carriers.Sum(c => c.PotentialSpiffTotal).ToString("C")</td>
<td>#Model[date].Carriers.Sum(c => c.EligibleActivationCount) / #Model[date].Carriers.Sum(c => c.ApprovedSpiffTotal).ToString("C")</td>
<td>#Model[date].Carriers.Sum(c => c.IneligibleActivationCount) / #Model[date].Carriers.Sum(c => c.UnpaidSpiffTotal).ToString("C")</td>
</tr>
for (int carrier = 0; carrier < Model[date].Carriers.Count; carrier++)
{
<tr class="date_#date date-hide" onclick="$('.submitted-#date-#carrier').toggleClass('carrier-hide');">
<td><span class="pull-left dash"><i class="fa fa-caret-up"></i></span> #Model[date].Carriers[carrier].Carrier</td>
<td>
<a onclick="pullDetails('#Model[date].Carriers[carrier].CarrierId', '#Model[date].Date', 'potential' ,'submitted-#date-#carrier')">
#(Model[date].Carriers[carrier].SubmittedActivationCount == 0 ? "--" :
Model[date].Carriers[carrier].SubmittedActivationCount + " / " +
Model[date].Carriers[carrier].PotentialSpiffTotal.ToString("C"))
</a>
</td>
<td>
<a onclick="pullDetails('#Model[date].Carriers[carrier].CarrierId', '#Model[date].Date', 'eligible' ,'submitted-#date-#carrier')">
#(Model[date].Carriers[carrier].EligibleActivationCount == 0 ? "--" :
Model[date].Carriers[carrier].EligibleActivationCount + " / " +
Model[date].Carriers[carrier].ApprovedSpiffTotal.ToString("C"))
</a>
</td>
<td>
<a onclick="pullDetails('#Model[date].Carriers[carrier].CarrierId', '#Model[date].Date', 'ineligible' ,'submitted-#date-#carrier')">
#(Model[date].Carriers[carrier].IneligibleActivationCount == 0 ? "--" :
Model[date].Carriers[carrier].IneligibleActivationCount + " / " +
Model[date].Carriers[carrier].UnpaidSpiffTotal.ToString("C"))
</a>
</td>
</tr>
<tr class="date_#date date-hide submitted-#date-#carrier carrier-hide carrier">
<td class="submitted_details" colspan="100%">
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<script>
$(function () {
$('.date-row').click(function () {
$(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});
});
$(function () {
$('.date-hide').click(function () {
$(this).find('i').toggleClass('fa-caret-down fa-caret-up');
});
});
function pullDetails(carrierId, startDate, status, divid) {
$.get("#Url.Action("getDelayedSpiffOrderDetails", "Dashboard")",
{ carrierId: carrierId, startDate: startDate, status: status },
function (data) {
$('.' + divid + ' .submitted_details').html(data);
$('.' + divid).removeClass('carrier-hide');
});
}
Try something like this
$("#startDate").change(function () {
// call your function here
});
Related
The below is part of a media player. Unfortunately, I cannot find the reason why the event listener is not registering the clicks on the hearts (when a user favorites a song). I have tried several implementations and I am researching for the last week with no success. Can you help?
How can I make the click listener to update the heart count?
HTML
<div class="player">
<div class="dashboard">
<header>
<p>Playing:</p>
</header>
<div class="cd">
<div class="cd-thumb">
</div>
</div>
<div class="control">
<div class="btn btn-random inactive">
<i class="fas fa-random"></i>
</div>
<div class="btn btn-prev">
<i class="fas fa-step-backward"></i>
</div>
<div class="btn btn-toggle-play">
<i class="fas fa-pause icon-pause"></i>
<i class="fas fa-play icon-play"></i>
</div>
<div class="btn btn-next">
<i class="fas fa-step-forward"></i>
</div>
<div class="btn btn-mute-unmute inactive">
<i class="fas fa-volume-up"></i>
</div>
</div>
</div>
<div class="playlist">
</div>
Script 1
render: function () {
let that = this;
fetch("hearts.txt")
.then(function(response) {
return response.json();
})
.then(function(heartCounts) {
let t = that.songs.map(
(t, e) => `
<div class="song ${
e === that.currentIndex ? "active" : ""
}" data-index="${e}">
<div class="thumb"
style="background-image: url('${t.image}')">
</div>
<div class="body">
<h3 class="title">${t.name}</h3>
<p class="author">${t.singer}</p>
</div>
<div class="heart" data-song-id="${e}">
<i class="fa fa-heart${
heartCounts[e] ? " active" : ""
}"></i> <span>${heartCounts[e] || 0}</span>
</div>
</div>
`
);
playlist.innerHTML = t.join("");
});
},
Script 2
const getHeartCounts = function () {
let xhr = new XMLHttpRequest();
xhr.open("GET", "return.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let heartCounts = JSON.parse(xhr.responseText);
// Update the heart count displays
document.querySelectorAll(".heart i + span").forEach((countDisplay, i) => {
countDisplay.innerHTML = heartCounts[i];
});
// Update the active heart icons
document.querySelectorAll(".heart i").forEach((heart, i) => {
if (heartCounts[i] > 0) {
heart.classList.add("active");
}
});
}
};
xhr.send();
};
document.addEventListener("DOMContentLoaded", function () {
// Add click listener to update the heart count
document.querySelectorAll(".heart").forEach(function (heart) {
heart.addEventListener("click", function (e) {
let target = e.target,
songIndex = parseInt(target.dataset.songId),
countEl = target.querySelector("span"),
heartCount = countEl ? parseInt(countEl.innerHTML) : 0,
isActive = target.classList.contains("active");
// Update the heart count
heartCount = isActive ? heartCount - 1 : heartCount + 1;
if (countEl) {
countEl.innerHTML = heartCount;
}
let heartIcon = target.querySelector("i");
if (heartIcon) {
heartIcon.classList.toggle("active", !isActive);
}
// Update the heart count on the server
let xhr = new XMLHttpRequest();
xhr.open("POST", "store.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("index=" + songIndex + "&count=" + heartCount);
});
});
// Update the heart counts on page load
getHeartCounts();
});
Goal: I have an ecommerce website. I'm working on the cart page. When the user wants to add one or remove one from the quantity they're buying, I want them to be able to press a plus or minus button on the page that will remove or add one without reloading the page.
Issue:
I have controllers to make this happen, but I don't know how to pass a specific model or the ID from the model, from the foreach loop all without reloading the page.
Here's the page:
#model IEnumerable<AirmotionEcommerceWebsite.TwebCartProduct>
#{
ViewBag.Title = "My Cart";
ViewBag.decSubtotal = 0;
ViewBag.decShipping = 68.99;
ViewBag.decStateTax = 0.078;
ViewBag.decTax = 0;
ViewBag.decTotal = 0;
}
<br />
<div class="container">
<h2>Cart</h2>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<div class="table-responsive">
<table class="align-content-lg-start table table-bordered" id="dataTable" width="100%" cellspacing="0">
<tbody>
#if (Model.Count() == 0)
{
<h1>Your cart is empty!</h1>
}
else
{
foreach (var item in Model)
{
ViewBag.decSubtotal += item.IntQuantity * item.IntWebProduct.DecMsrp;
<tr>
<td class="text-left">#item.IntWebProduct.StrProductName</td>
<td class="text-left">#item.IntWebProduct.DecMsrp.ToString("c")</td>
<td class="text-left">
#Html.ActionLink("add_circle_outline", "AddOneToCart", new { intWebProductID = item.IntWebProductId }, new { #class = "material-icons" })
#item.IntQuantity.ToString()
#Html.ActionLink("remove_circle_outline", "RemoveOneFromCart", new { intWebProductID = item.IntWebProductId }, new { #class = "material-icons" })
#Html.ActionLink("delete", "RemoveAllFromCart", new { intWebProductID = item.IntWebProductId }, new { #class = "material-icons float-right" })
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
<h2>Order Summary</h2>
</div>
<ul class="list-group list-group-flush">
#{
//ViewBag.decTax = ViewBag.decSubtotal * (decimal)ViewBag.decStateTax;
ViewBag.decTotal = (decimal)ViewBag.decSubtotal + (decimal)ViewBag.decShipping;/* + ViewBag.decTax;*/
}
<li class="list-group-item">Subtotal<span class="float-right">#ViewBag.decSubtotal.ToString("c")</span></li>
<li class="list-group-item">Shipping<span class="float-right">#ViewBag.decShipping.ToString("c")</span></li>
#*<li class="list-group-item">Tax<span class="float-right">#ViewBag.decTax.ToString("c")</span></li>*#
<li class="font-weight-bold list-group-item">
Total<span class="float-right">#ViewBag.decTotal.ToString("c")</span>
<br />
<br />
#Html.ActionLink("Checkout", "Checkout", "Home")
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
I want them to be able to press a plus or minus button on the page that will remove or add one without reloading the page.
Firstly,you can use js to change the html code.But you cannot use set ViewBag with js variable,so when checkout,you need to use url to pass decSubtotal and decTotal.Here is a demo:
#{
ViewBag.Title = "My Cart";
ViewBag.decSubtotal = 0;
ViewBag.decShipping = 68.99;
ViewBag.decStateTax = 0.078;
ViewBag.decTax = 0;
ViewBag.decTotal = 0;
}
<br />
<div class="container">
<h2>Cart</h2>
<div class="card-body">
<div class="row">
<div class="col-md-8">
<div class="table-responsive">
<table class="align-content-lg-start table table-bordered" id="dataTable" width="100%" cellspacing="0">
<tbody>
#if (Model.Count() == 0)
{
<h1>Your cart is empty!</h1>
}
else
{
foreach (var item in Model)
{
ViewBag.decSubtotal += item.IntQuantity * item.IntWebProduct.DecMsrp;
<tr>
<td class="text-left">#item.IntWebProduct.StrProductName</td>
<td class="text-left">#item.IntWebProduct.DecMsrp.ToString("c")</td>
<td class="text-left">
<button onclick="Add(this,#item.IntWebProduct.DecMsrp)" class = "material-icons">add_circle_outline</button>
<span>#item.IntQuantity</span>
<button onclick="Remove(this,#item.IntWebProduct.DecMsrp)">remove_circle_outline</button>
<button onclick="Delete(this,#item.IntWebProduct.DecMsrp)">RemoveAllFromCart</button>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">
<h2>Order Summary</h2>
</div>
<ul class="list-group list-group-flush">
#{
//ViewBag.decTax = ViewBag.decSubtotal * (decimal)ViewBag.decStateTax;
ViewBag.decTotal = (decimal)ViewBag.decSubtotal + (decimal)ViewBag.decShipping;/* + ViewBag.decTax;*/
}
<li class="list-group-item">Subtotal<span class="float-right" id="Subtotal">#ViewBag.decSubtotal.ToString("c")</span></li>
<li class="list-group-item">Shipping<span class="float-right" id="Shipping">#ViewBag.decShipping.ToString("c")</span></li>
#*<li class="list-group-item">Tax<span class="float-right">#ViewBag.decTax.ToString("c")</span></li>*#
<li class="font-weight-bold list-group-item">
Total<span class="float-right" id="Total">#ViewBag.decTotal.ToString("c")</span>
<br />
<br />
<a id="Checkout" asp-controller="Home" asp-action="Checkout">Checkout</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
#section scripts
{
<script>
var decSubtotal = #ViewBag.decSubtotal;
var decShipping =#ViewBag.decShipping;
var decTotal=#ViewBag.decTotal;
function Add(t, price) {
decSubtotal += price;
change();
$(t).next()[0].innerText = parseInt($(t).next()[0].innerText) + 1;
}
function Remove(t, price) {
decSubtotal -= price;
change();
if (parseInt($(t).prev()[0].innerText) == 1) {
$(t).parent().parent().remove();
} else {
$(t).prev()[0].innerText = parseInt($(t).prev()[0].innerText) - 1;
}
}
function Delete(t, price) {
decSubtotal -= parseInt($(t).prev().prev()[0].innerText) * price;
change();
$(t).parent().parent().remove();
}
function change() {
decTotal = decSubtotal + decShipping;
var temp = document.getElementById("Subtotal").innerText.substr(0, 1);
document.getElementById("Subtotal").innerText = temp + decSubtotal.toFixed(2);
document.getElementById("Total").innerText = temp + decTotal.toFixed(2);
if ($("#Checkout").attr("href").includes("?")) {
href = href.split("?")[0];
}
$("#Checkout").attr("href",href + "?decSubtotal=" + decSubtotal.toFixed(2) + "&&decTotal=" + decTotal.toFixed(2));
}
</script>
}
action:
public IActionResult Checkout(decimal decSubtotal, decimal decTotal)
{
return Ok();
}
result:
I am making a dog shelter app, so I saved all the images URL in the database. So far, this is what I have:
What I want is instead of showing this P I want to show the dog's photo.
My code:
index.html
<div id="template_especie_show">
<nav class="navbar navbar-fixed-top df-nav cen col-md-12" role="navigation" style="">
<ul class="nav navbar-nav" style="width: 100%">
<li class="pull-left"><button type="button" id="especie_menu_left" class="btn btn-default btn-menu">Voltar</button></li>
<li class="pull-left"><button type="button" id="especie_menu_logout" class="btn btn-default btn-menu-logout">Sair</button></li>
<li style="float: none; display: inline-block; position: relative; text-align: center"><img src="img/icone_ap.png" height="47"></li>
</ul>
</nav>
<div class="row vert-offset-top-30"></div>
<div class="col-md-2"></div>
<div class="col-md-8">
<div style="text-align: center"><h2><span id="animal_show_name"></span></h2></div>
<div class="input-group">
<div class="input-group-addon">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</div>
<input type="text" id="table_especie_search" class="form-control" placeholder="Procurar animais">
</div>
<table class="table table-hover" id="table_especie">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="col-md-2"></div>
</div>
script.js
var tableEspecie= $('#table_especie').DataTable({
"paging": false,
"info": false,
"order": [
[2, "asc" ],
[3, "asc"],
[1, "asc"]
],
"columnDefs": [
{ "visible": false, "targets": 0 },
{ "visible": false, "targets": 2 },
{ "visible": false, "targets": 3 }
],
"drawCallback": function () {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( especie, i ) {
if ( last !== especie) {
$(rows).eq( i ).before(
'<tr class="especie info"><td colspan="4">'+especie+'</td></tr>'
);
last = especie;
}
} );
$("#table_especie thead").remove();
$("#table_especie tfoot").remove();
}
});
var populateEspecieShowName = function(data) {
$('#animal_especie_name').text(data[0].name);
};
var populateEspecieTable = function(data) {
var animais = [];
$.each(data, function(id_animal, animal){
animais.push([
animal.id_animal,
animal.nome_animal + ': ' + '<br>' + animal.notas_animal,
animal.nome_animal.charAt(0).toUpperCase()
]);
});
$('#table_especie').dataTable().fnClearTable();
$('#table_especie').dataTable().fnAddData(animais);
$('#table_especie').dataTable().fnDraw();
};
$('#table_especie tbody').on( 'click', 'tr', function () {
var animalId = $('#table_especie').DataTable().row(this).data();
if (animalId !== undefined)
$.route('animal/' + animalId[0]);
});
$('#table_especie_search').keyup(function(){
$('#table_especie').DataTable().search($(this).val(), false, true).draw() ;
});
route.js
case 'especie_show':
setButton('left', template, 'especies', 'redirect', null);
setButton('right', template, 'especie/' + pathArray[1] + '/edit', 'redirect', null);
var params = 'filter=id_especie%3D' + pathArray[1] + '&fields=nome_especie';
$.api.getRecords('especie', params, getToken('token'), populateEspecieShowName);
params = 'filter=especie_id_especie%3D' + pathArray[1] + '&fields=nome_animal, notas_animal';
$.api.getRecords('animal', params, getToken('token'), populateEspecieTable);
break;
Thanks everyone for the attention and help!
I don't know how your data is structured, but you would need a url for each dog in the shelter.
[{"name":"fido",
"img":"some url"},
{"name":"woofer",
"img":"some 2nd url"},
{"name":"champ",
"img":"some 3rd url"
}]
You would pull that info into your js. Then you would loop over each item and set the image tag source attribute accordingly.
for(var i = 0; i < arrayOfDogs.length; i++){
(your img node).src = arrayOfDogs[i].url;
}
It looks like you're using jQuery. So you can create a template and when you loop over the data, append a new row/cell/header/whatever to the table or div
What I did was, instead of having just the image URL in the database I put the complete HTML reference, for example:
<img src="http://i.imgur.com/OrK7thb.jpg" alt="Heidi" style="width:304px;height:228px;">
Thanks for the help you guys, I hope anyone who is having the same problem can solve it like this.
So i am developing this app in which i want to apply pagination to list of templates.
template objects are stored in the list.
I am displaying thumbnails of templates on the page and i want to apply pagination for this page.
so far I have tried following solution but it didn't work.
list.html
<div class="container">
<div class="homepage-header">
<h2 class="homepage-title text-center wow fadeInDown animated" style="visibility: visible; animation-name: fadeInDown; -webkit-animation-name: fadeInDown;"> TEMPLATES </h2>
</div>
<div class="row">
<div class="col-md-6 col-sm-6" style="text-align: left">
<div class="form-inline">
<div class="form-group has-feedback has-clear">
<input type="text" class="form-control" ng-model="searchParam" ng-model-options="{ debounce: 400 }" placeholder="Search template ..."
/>
<a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="searchParam = '';
retreivePageData(0);" ng-show="searchParam" style="pointer-events: auto; "></a>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6" style="text-align: right; padding-right: 30px;">
<div class="form-inline">
<label>
<input type="radio" ng-model="selectedOption" value="All" ng-change="retrieveTemplates(selectedOption)"> All
</label>
<label>
<input type="radio" ng-model="selectedOption" value="Annotate" ng-change="retrieveTemplates(selectedOption)"> Annotate
</label>
<label>
<input type="radio" ng-model="selectedOption" value="Rapid" ng-change="retrieveTemplates(selectedOption)"> Component
</label>
</div>
</div>
</div>
<div class="homepage-ui-showcase-2-css row wow zoomIn animated" style="height: 402px;padding: 5px 0px; visibility: visible; animation-name: zoomIn; -webkit-animation-name: zoomIn;">
<div ng-repeat="(templateIndex, templateModel) in templatesList | filter:searchParam | limitTo: itemsPerPage">
<div class="active col-md-3 col-lg-3 col-sm-6 col-xs-12 mix design painting" style="display: inline-block;padding-top: 10px;"
ng-init="visible=false" ng-mouseover="visible=true" ng-mouseleave="visible=false">
<div class="portfolio-item shadow-effect-1 boxShadow" style="max-width: 250px;padding:0.3px;border:2px dotted #bebede;cursor: pointer">
<div class="mainBadge">
<kbd>{{templateModel.type}}</kbd>
</div>
<div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
<div ng-switch-when="false" style="height: 130px;" ui-sref="/designer/:pageId({pageId:templateModel.id})" class="portfolio-img ">
<i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-puzzle-piece fa-4x"></i>
</div>
<div ng-switch-when="true" style="height: 130px;" ui-sref="annotator/:annotatedTemplateId({annotatedTemplateId:templateModel.id})"
class="portfolio-img ">
<i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-file-image-o fa-4x"></i>
</div>
</div>
<div class="portfolio-item-content" title="{{templateModel.name}}">
<h3 class="header" style="font-size: 13px;text-align: center;display:inline;">
{{templateModel.name}}
</h3>
<small class="pull-right" ng-show="visible" style="display: inline; padding-top: 4px">
<div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
<div ng-switch-when="true" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
ui-sref="generateCommunication({mode:'A',id: templateModel.id})"
ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
<i class="fa fa-file-pdf-o"></i>
</div>
<div ng-switch-when="false" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
ui-sref="generateCommunication({mode:'T',id: templateModel.id})"
ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
<i class="fa fa-file-pdf-o"></i>
</div>
</div>
</small>
</div>
</div>
</div>
</div>
</div>
<div class="row " style="margin-top: 10px; padding-top:0px;">
<div class="pagination-div pull-right" style="">
<uib-pagination ng-model="currentPage" total-items="totalItems" max-size="maxSize" boundary-links="true">
</uib-pagination>
</div>
</div>
list.controller.js
'use strict';
angular.module('rapid').controller('HomeListController',
function($scope, $rootScope, $window, $uibModal, ServiceFactory, toaster, ReadFileService, AnnotationService, AnnotateService, DocumentService) {
$scope.templatesList = [];
$scope.filteredTemplates = [];
$scope.selectedOption = 'All';
$scope.annotateTemplateMeta = [];
$scope.rapidTemplateMeta = [];
$scope.init = function() {
$scope.selectedOption = "All";
//$scope.options = [{'label':'All', 'value':'All'}, {'label':'Annotate', 'value':'Annotate'}, {'label':'Component', 'value':'Component'}];
$scope.retrieveTemplates('All');
$scope.currentPage = 1;
};
$scope.retrieveTemplates = function(selectedOption) {
$scope.templatesList = [];
if (selectedOption === 'Annotate') {
$scope.fetchAnnotationTemplates(selectedOption);
} else if (selectedOption === 'Rapid') {
$scope.fetchRapidTemplates(selectedOption);
} else {
$scope.fetchAnnotationTemplates(selectedOption);
}
};
$scope.fetchAnnotationTemplates = function(selectedOption) {
AnnotateService.get().$promise.then(function(result) {
$scope.annotateTemplateMeta = result[0];
console.log('Annotated template count :: ' + result[0].length);
if (selectedOption === 'All') {
$scope.fetchRapidTemplates(selectedOption);
} else {
$scope.prepareTemplateList(selectedOption);
}
});
};
$scope.fetchRapidTemplates = function(selectedOption) {
ServiceFactory.PagesService.getAllPages().$promise.then(function(result) {
$scope.rapidTemplateMeta = result[0];
console.log('Rapid template count :: ' + result[0].length);
$scope.prepareTemplateList(selectedOption);
});
};
$scope.prepareTemplateList = function(selectedOption) {
$scope.itemsPerPage = 8;
var getPaginatedTemplateList = 'getList';
//$scope.currentPage = 0;
if (selectedOption === 'Annotate') {
$scope.annotateTemplateMeta.forEach(function(annotate) {
var templateObject = {};
templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity: annotate.dynamic_entity };
$scope.templatesList.push(templateObject);
});
} else if (selectedOption === 'Rapid') {
$scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
var templateObject = {};
templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity: rapidTemplate.pageObj.entity };
$scope.templatesList.push(templateObject);
});
} else {
$scope.annotateTemplateMeta.forEach(function(annotate) {
var templateObject = {};
templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity: annotate.dynamic_entity };
$scope.templatesList.push(templateObject);
});
$scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
var templateObject = {};
templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity: rapidTemplate.pageObj.entity };
$scope.templatesList.push(templateObject);
});
$scope.totalItems = $scope.templatesList.length;
$scope.maxSize = 5;
}
console.log($scope.templatesList);
console.log($scope.currentPage);
};
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
alert('Page changed to: ' + $scope.currentPage);
$log.log('Page changed to: ' + $scope.currentPage);
};
$scope.init();
$scope.$watch('currentPage + numPerPage', function() {
console.log('is it coming.....?');
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage)
, end = begin + $scope.itemsPerPage;
$scope.filteredTemplates = $scope.templatesList.slice(begin, end);
});
});
is there anything wrong with my code?
please provide some inputs on this.
See how to create a custom paging which will deal with the performance and you will have control on the paging control style.
Create a service to set a paging object
var rapid = angular.module('rapid');
rapid.service('pagerOptions', function () {
'use strict';
return {
newOptions: function () {
return {
totalItems: 0,
itemsPerPage: 50,
page: 1,
sortBy: '',
isASC: true,
filters: null,
sortOptions: {
by: '',
isASC: true,
sort: function (sortBy) {
if (sortBy === this.parent.sortBy) {
this.parent.isASC = !this.parent.isASC;
} else {
this.parent.sortBy = sortBy;
this.parent.isASC = true;
}
this.parent.resetPage();
if (typeof this.parent.onPageChange === "function")
this.parent.onPageChange();
}
},
resetPage: function () {
this.page = 1;
},
goToPage: function (page) {
this.page = page;
if (typeof this.onPageChange === "function")
this.onPageChange();
},
init: function () {
this.sortOptions.parent = this; // it allows the Methods object to know who its Parent is
delete this.init; // if you don't need the Init method anymore after the you instanced the object you can remove it
return this; // it gives back the object itself to instance it
}
}.init();
}
};
})
Create a custom directive to design paging template as follows,
rapid.directive('footerPager', function () {
return {
restrict: 'E',
transclude: true,
template:
'<div class="col-xs-9 text-right" ng-cloak>\
<span ng-if="options.totalItems > options.itemsPerPage">\
<pagination \
ng-model="options.page" \
total-items="options.totalItems" \
items-per-page="options.itemsPerPage" \
ng-change="options.goToPage(options.page)" \
max-size="5" rotate="false" boundary-links="true" \
previous-text="‹" next-text="›" \
first-text="«" last-text="»" \
class="pagination-sm">\
</pagination>\
</span>\
</div>\,
scope: {
options: '='
}
}
});
In cshtml file use the above created custom directive as follows,
<footer-pager options="pagingOptions" id="footer"/>
In corresponding controller.js file create and set the 'pagerOptions' object by calling the 'newOptions' method of the above created service,
rapid.controller('HomeListController',
['$scope', 'adminSvc','pagerOptions',
function auditLogCtrl($scope,adminSvc,pagerOptions) {
$scope.pagingOptions = pagerOptions.newOptions();
$scope.pagingOptions.sortBy = "CreatedDate";
$scope.pagingOptions.itemsPerPage = 10;
$scope.pagingOptions.onPageChange = loadData; //loadData is a method load the data to the page.
var numberOfSearchPerfomed = 0;
$scope.data= {};
function loadData() {
$scope.pagingOptions.filters = selectedFilters;
service.getData(vm.pagingOptions) //Method will fetch data from db and show in the view based on pagingOptions.
.success(function (result) {
$scope.data= result.Data;
$scope.pagingOptions.totalItems = result.TotalCount; // TotalCount represents the total number of records not page wise.
$scope.enableResetButton = numberOfSearchPerfomed >= 1;
});
}
loadData();
}])
(function ($) {
$.fn.fCycle = function () {
var x;
for (x in arguments) {
$(arguments[x]).close();
}
$(this).collapse("show");
};
$(".btn-next").on('click', function() {
var form = [$("#name"), $("#surname"), $("#student_number"), $("#cellphone"), $("#email"), $("#course"), $("#year")],
i = 0,
a = "#" + $(this).attr("data-to"),
b = "#" + $(this).attr("data-from");
if ($(this).hasClass("to_course")) {
for (i; i < 5; i++) {
console.log(form[i].val());
if (form[i].val() === undefined) {
form[i].addClass("has-danger")
$(a).fCycle(b);
} else if (form[i].hasClass("has-danger") && form[i].length > 0) {
form[i].removeClass("has-danger")
}
}
$(a).fCycle(b);
}
});
}(jquery));
$(".btn-next").on('click', function () {
var form = [$("#name")],
i = 0,
a = "#" + $(this).attr("data-to"),
b = "#" + $(this).attr("data-from");
if ($(this).hasClass("to_course")) {
for (i; i < form.length; i++) {
if (form[i].val() === undefined) {
form[i].addClass("has-danger")
$(a).fCycle(b);
}
else if (form[i].hasClass("has-danger") && form[i].length > 0) {
form[i].removeClass("has-danger");
}
}
$(a).fCycle(b);
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet"/>
<form method="post" id="apply">
<div id="personal" class="collapse in">
<fieldset class="col-xs-10 col-xs-offset-1 form-group">
<div class="row">
<label for="names">Name(s)</label>
<input class="form-control" type="text" name="names" id="names" placeholder="Enter your full name here">
</div>
<hr>
<div class="row">
<nav>
<ul class="pager">
<li>
<button class="btn btn-danger btn-cancel" type="button">cancel</button>
</li>
<li class="pager-next">
<button class="btn btn-next btn-success to_course" type="button" data-to="course" data-from="personal">next</button>
</li>
</ul>
</nav>
</div>
</fieldset>
</div>
<div id="course" class="collapse">
<p>course</p>
</div>
</form>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above snippet doesn't seem to work at all - in the case of the Original (http://alpha.msauwc.co.za -> if you click on the Join the MSA button,
You'll find that the form does work. The issue is that the next button should not be working when the input fields have not been filled.
This has to be prevented using jquery.
Try defining your array with just selector strings, and then wrapping your form[i] objects like:
$(form[i]).val(), $(form[i]).addClass('has-danger'), etc
You can use these methods to disable & activate the button:
$(".btn-next").addClass('disabled') // when you want to disable it
$(".btn-next").removeClass('disabled') // when you want to activate it