Using Django Models to assign HTML div through jQuery - javascript

for the last few days I've been trying to create a method in jquery using django models and I have found myself to be very out of my depth and would appreciate and explanation I can get. So currently I have a django model that has the following information : name, date, location, semester. I use the first 3 pieces of information in displaying my html, however, I want to use 'semester' to see what div tag my items go into.
The semester tag can either return 'Fall' or 'Spring' values is there a way I can use this to assign the components to the correct div. So if semester is Fall then it should go into the div with the id 'fall-races' and if its spring it should go to 'spring-races'
Currently I only have a jquery working where I get all the elements and assign it to the other div.
Thank you for your help and any possible advice.
<div class="flex-column">
<div class="header shadow-lg">
<h1 class="text-center py-3">
Fall Schedule
</h1>
</div>
<div id="fall-races">
{% for race in race %}
<div class="regatta-card my-2 mx-2 ">
<h2 class="center-text py-2">{{ race.date }}</h2>
<h1 class="text-center my-2">{{ race.name }}</h1>
<h3 class="text-center mb-3">{{ race.location}}</h3>
<h6 class="text-center">Recap</h6>
</div>
{% endfor %}
</div>
<input type="button" onclick="findChildren()" value="Click it" />
<div class="header shadow-lg">
<h1 class="text-center py-3">
Spring Schedule
</h1>
</div>
<div id="spring-races">
</div>
</div>
<script>
function findChildren() {
var objChl = document.getElementById('fall-races').children;
var msg = document.getElementById('spring-races');
msg.innerHTML = '';
for (i = 0; i < objChl.length ; i++) {
msg.appendChild(objChl[i]);
}
}
</script>

Maybe you want something like this:
Html:
<!-- Some html stuff -->
<div id="fall-races">
{% for race in race %}
<div class="regatta-card my-2 mx-2 ">
<h2 class="center-text py-2">{{ race.date }}</h2>
<h1 class="text-center my-2">{{ race.name }}</h1>
<h3 class="text-center mb-3">{{ race.location}}</h3>
<h6 class="text-center">Recap</h6>
<input type="hidden" value="{{race.semester}}" />
</div>
{% endfor %}
</div>
<!-- Some html stuff -->
JS:
<script>
function findChildren() {
var parent = document.getElementById('fall-races');
var objChl = parent.children;
var msg = document.getElementById('spring-races');
msg.innerHTML = '';
for (i = 0; i < objChl.length ; i++) {
const element = objChl[i];
var value = element.getElementsByTagName("input")[0].value;
if (value==="Spring"){
msg.appendChild(element);
parent.removeChild(element);
}
}
}
</script>
This is like the simplest way to achieve that, hope it helps you.

Related

Chart js multiple pie chart on one page

Iam building my portfolio website and i build a simple stocktracker. I added some charts from Chart.js, but somehow only one gets rendered when I excecute the code.
I managed to assign all the divs and data dynamically by making the variables dynamic. I did this by adding the portfolio id in the for loop. I can't figure out why its not working. Appreciate any help.
{% extends 'base.html' %}
{% block page_content %}
{% if user.is_authenticated %}
<body>
<div class="container">
<div class="row">
<div class="col-12">
<h2>
Welcome to the stocktracker
</h2>
<p>I build this stocktracker app to learn database operations. To get current stock data, I linked this to
the free API from Polygon.io. It's only possible to do 5 API calls per minute. You will see an error
message whenever the api calls are exceeded.
<br><br>Current features are:
<ol>
<li>Basic CRUD database operation</li>
<li>Adding portfolio's linked to user</li>
<li>Only show portfolio's linked to user</li>
<li>Show general KPI's in portfolio overview</li>
<li>KPI's calculated based on positions in portfolio</li>
<li>Adding position to portfolio</li>
<li>API connection with Polygon.io to get live stock data</li>
<li>Chart.js integration for visual representation of portfolio metrics</li>
</ol>
</p>
</div>
</div>
<div class="row">
<div class="col-8">
<h2>Select your portfolio</h2>
</div>
<div class="col-4 text-end">
<!-- Button trigger modal -->
<button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#addPortfolioModal">
Add new portfolio
</button>
<!-- Modal -->
<div class="modal fade" id="addPortfolioModal" tabindex="-1" role="dialog"
aria-labelledby="addPortfolioModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addPortfolioLabel">Modal title</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form name="portfolio_form" method="post">
{% csrf_token %}
<p>
{{ portfolio_form }}
</p>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close
</button>
<input type="submit" value="Submit"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div>
{% for portfolio in portfolios %}
<div class="row pt-4">
<div class="col-6">
<a class="btn btn-primary" href="{% url 'portfolio_detail' portfolio.pk%}">Go to {{ portfolio }}</a>
</div>
</div>
{% if portfolio.total_positions > 0 %}
<div>
{% load static %}
<div class="col-4 text-start" style="width: 50%;">
<canvas id="pie-chart{{ portfolio.pk }}"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<script>
var randomNum_{{ portfolio.pk }} = () => Math.floor(Math.random() * (235 - 52 + 1) + 52);
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
countPositions = {{ portfolio.total_positions|safe }};
var barColors_{{ portfolio.pk }} = [];
for (let i = 0; i < countPositions; i++) {
randomGeneratedColor = rgbToHex(randomNum_{{ portfolio.pk }}(), randomNum_{{ portfolio.pk }}(), randomNum_{{ portfolio.pk }}());
while (barColors_{{ portfolio.pk }}.includes(randomGeneratedColor)) {
randomGeneratedColor = rgbToHex(randomNum(), randomNum(), randomNum());
}
barColors_{{ portfolio.pk }}.push(randomGeneratedColor);
}
var config_{{ portfolio.pk }} = {
type: 'pie',
data: {
datasets: [{
data: {{ portfolio.data_for_chart_array|safe }},
backgroundColor: barColors_{{ portfolio.pk }},
label: 'Stock ticker'
}],
labels: {{ portfolio.labels_array|safe }}
},
options: {
responsive: true
}
};
window.onload = function() {
var ctx = document.getElementById('pie-chart{{ portfolio.pk }}').getContext('2d');
window.myPie = new Chart(ctx_{{ portfolio.pk }}, config_{{ portfolio.pk }});
};
</script>
</div>
</div>
{% endif %}
<div class="row">
<div class="col-4 pt-2">
<b>Total amount invested:</b> {{ portfolio.total_amount_invested }}
<br><b>Positions:</b> {{ portfolio.total_positions }}
<br><b>Profit:</b> {{ portfolio.total_profit }}
<br><b>Profit in %:</b> {{ portfolio.total_profit_percentage }} %
</div>
</div>
</div>
{% endfor %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
</div>
</body>
{% endif %}
{% endblock %}
Somehow only the last chart gets rendered instead of all three.
You have a loop there, and in each iteration of the loop, you're using window.onload = function() {…};
Basically, you're overwriting the onload function at each iteration of the loop, so only the last overwrite survives.
What you want is to add load event listeners on the window instead of continually overwriting one single listener.
To achieve this, I would recommend replacing this:
window.onload = function () {…}
with this:
window.addEventListener('load', function() {…})`
See addEventListener
Another way of seeing that window.onload = function () {…} is problematic is the following snippet:
window.onload = function () { alert('one') };
window.onload = function () { alert('two') };
Q: What do you expect to happen on page load here?
A: Similarly to your case, only the second function (alerting "two") will be called.

How to change contents on clicking the selected div using Javascript?

I am new to Javascript. I wish to change the contents of div on selecting a particular div element.
If I select a div, the text associated with that div contents only should display. I am using a loop to display the contents. It's like a chat application. If a user clicks on a contact the messages associated with that user should display. I am using a loop to display messages and users.
What I have tried is:
Twig code:
{% set msg = query().from('messages').get() %}
{% set to_add =to_name %}
{% set to_details = query().from('users_users').where('id', to_add).get() %}
<div class="container">
<h3 class=" text-center">Messaging</h3>
<div class="messaging">
<div class="inbox_msg">
<div class="inbox_people">
<div class="headind_srch">
<div class="recent_heading">
<h4>{{auth_user().first_name}}</h4>
</div>
<div class="srch_bar">
<div class="stylish-input-group">
<input type="text" class="search-bar" placeholder="Search" >
<span class="input-group-addon">
<button type="button"> <i class="fa fa-search" aria-hidden="true"></i> </button>
</span> </div>
</div>
</div>
<div class="inbox_chat">
{% set newArray = [] %}
{% for msg in msg_details %}
{% if msg.to_name not in newArray %}
<div class="chat_list active_chat" onclick=viewMessage(this)>
<div class="chat_people">
<div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
<div class="chat_ib">
<h5>{{msg.to_name}} <span class="chat_date">{{msg.time}}</span></h5>
</div>
</div>
</div>
{% set newArray = newArray|merge([msg.to_name]) %}
{% endif %}
{% endfor %}
</div>
</div>
<div class="mesgs">
<div class="msg_history">
<div class="incoming_msg">
<div class="incoming_msg_img">
<img src="https://ptetutorials.com/images/user-profile.png" alt="sunil">
</div>
<div class="received_msg">
<div class="received_withd_msg">
<p>{{msg.message}}</p>
<span class="time_date">{{msg.time}}</span></div>
</div>
</div>
<div class="outgoing_msg">
<div class="sent_msg">
<p></p>
<span class="time_date"></span> </div>
</div>
</div>
</div>
</div>
</div></div>
Javascript code:
<script>
function copyText(elementId){
var x = document.getElementById(elementId).textContent;
if(document.getElementById('select-text').value.length == 0)
{
document.getElementById("btn").disabled = false;
document.getElementById(elementId).style.backgroundColor = "lightblue";
document.getElementById('select-text').focus();
document.getElementById('select-text').value += x;
}
else{
document.getElementById('select-text').readOnly = true;
}
}
</script>
What my output looks like
Output
My output shows all the messages, I want to show only the particular user message. How to do so?
What my table looks like:
Table
First of all you have to fetch the data from your table using a query something like to ensure you will get one record from each from_id.
SELECT * FROM msg GROUP BY from_id;
Then you can loop in twig to create the left side elements like,
{% for distinctMsg in distinctMsgs %}
<div class="chat_list active_chat" data-userId="{{ distinctMsg.fromId }}">
<div class="chat_people">
<div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
<div class="chat_ib">
<h5>{{distinctMsg.to_name}} <span class="chat_date">{{distinctMsg.time}}</span></h5>
</div>
</div>
</div>
{% endfor %}
Then in your javascript:-
$(".chat_list").on("click", function(){
// have a look here https://stackoverflow.com/questions/5309926/how-can-i-get-the-data-id-attribute
var userId = $(this).data( "userId" );
// Maybe display a loading icon in the right side div
$.ajax({
type: "POST",
url: "/api/msg/user/history", // your controller url
dataType: 'json',
headers: {
// if you have any headers to set
"Authorization": "Bearer {{ token }}"
},
data:{
"userId" : userId
}
})
.done(function (response) {
// stop displaying the loading icon
// process the response and display message history in right side
})
.fail(function (xhr, status, error) {
// show proper error message
});
});
NOTE: You will have to have jQuery in your page for Ajax functions to work.

jquery use diferente variables in the same <p> from fields from database

http://prntscr.com/ir16ez
I have a problem, i cannot put diferent amounts in my shopping cart because when i choose a quantity, the program take what i choose and does the result for money etc,(working fine here) and brings the quantity to the shopping cart named "encomenda" but when i add a diferent item, the quantity changes to all instead of changing to only one, ssry from my english
//shopping cart html
<div class="rightdiv">carrinho
<div id="encomenda" class="expandContent">
<h3 class="header">
<div class="headerColumn1">Encomenda</div>
<div class="headerColumn2 expand"><img src="img/plus.png"/></div>
<div class="expandedContentClearFloat"></div>
</h3>
<div class="expandedContent">
{% for item in data %}
<div class="product-removal">
<article class="product">
<header>
<img src="{{ item.img|e }}" class="iconcomp">
</header>
<div class="content">
<h1>{{ item.marca|e }}</h1>
{{ item.descr|e }}
</div>
<footer class="content">
<h2 class="full-price fixed fixed-encomenda">
{{ item.preco_unit|e }}€
</h2>
<p class='quantidade' ></p> **//shows the amount here**
<a class='pull-right adicionar adicionar-encomenda' data-id='{{ item.id|e }}'
data-preco='{{ item.preco_unit|e }}' data-modelo="{{ item.modelo|e }}" data-marca="{{ item.marca|e }}" data-descr="{{ item.descr|e }}">
<h2 class="full-price">
{{ item.preco_unit|e }}€
</h2>
</a>
<h2 class="price">
{{ item.preco_unit|e }}
</h2>
</footer>
</article>
</div>
{% endfor %}
<h1 id='valor_configuracao' class='pull-right' value='data-preco'>0</h1>
</div>
<input type="button" id="enviar" value="enviar" data-mensagem="ola">
</div>
</div>
//add disco for example
$('.adicionar-disco').click(function () {
id = $(this).data('id');
var allExceptClicked = $('.adicionar-disco').not(this);
AdicionarItem(allExceptClicked, "disco", "disco2");
$(this).data('quantidade', parseFloat($(this).parent().find("span.qt").text()));
$(this).parent().parent().find("button.close-disco").data('quantidade', parseFloat($(this).parent().find("span.qt").text()));
preco = preco + ($(this).data("preco")* $(this).data('quantidade'));
p=$(this).data('quantidade'); **//receive in p the amount**
var rounded = Math.round((preco) * 100) / 100;
$('#valor_configuracao').html(rounded);
$('.adicionar-encomenda').each(function () {
var productRow = $(this).parent().parent();
var i = $(this).data('id');
if (i == id) {
productRow.show();
alert(p);
$(".quantidade").text(p);**//give the <p> variable that is in the "encomenda" p that has the amount needed**
//$("p").attr(".quantidade",p);
//Marcar item como selecionado
$(this).attr("data-selecionado","sim");
}
});
});
the statement $(".quantidade").text(p) set the same value at all element with class="quantitade", and all item of your chart have class="quantitade".
You should uniquely identify the div where you want to set the value, with id attribute, if possible, generated with the product id.

How to Change Data from the right side to the left by clicking using EF

I want to know how can I change my data from the right side to the left by clicking correctly using Entity Framework. The data is in spanish, sorry for that but I can´t change it.
Here is my View where I can only change the "Titulo" that means in enlgish Title and the Content but I have problem with my DateTime and my Images that become a related table and with int data. The Id change because it appears in the right side (I dont want to show the Image and Id data in the right side).
To show the principal Image I use this #foreach where I get the data from the second table called "Noticias1" that means in english News1 where are the Image data for every News and if (img != null && img.Nombre.Equals(#principalId+"_0")) to show me only the Principal Img that is equal to the selected Id (I will show the others Img behind the content.)
Here the code
#foreach (var n in Model)
{
var img = n.Noticias2.FirstOrDefault();
if (img != null && img.Nombre.Equals(#principalId+"_0"))
{
var imgRuta = #img.Ruta+#img.Nombre+#img.Extension;
<img id="currentprincipalImagen" src="#imgRuta" class="img-responsive" alt="Imagen de Marte" />
<figcaption>
<p id="currentPrincipalImagenTitulo">#img.Descripcion</p>
</figcaption>
}
}
Here is my full view code
#{
var format = "dddd, MMMM dd, yyyy";
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPage.cshtml";
int principalId = Model[0].IdNoticia;
string principalTitulo = Model[0].Titulo;
string principalContenido = Model[0].Contenido;
DateTime principalFechaDesde = Convert.ToDateTime(Model[0].FeDesde);
DateTime principalFechaHasta = Convert.ToDateTime(Model[0].FeHasta);
}
<script type="text/javascript">
function changeDisplay(e) {
var principalTitulo = $(e).text();
var principalContenido = $(e).siblings(".Contenido:first").html();
var principalId = $(e).siblings(".IdNoticia:first").html();
var principalFechaDesde = $(e).siblings(".FeDesde").html();
$("#currentprincipalTitulo").html(principalTitulo);
$("#currentprincipalContenido").html(principalContenido);
$("#currentprincipalId").html(principalId);
$("#currentprincipalFechaDesde").html(principalFechaDesde);
}
</script>
<!-- Principal -->
<div class="col-md-12 main">
<div class="header sec-title-hd">
<div class="bg-calendar"></div>
<div class="col-md-7">
<h5 class="pull-left">NOTICIAS</h5>
<div>
<img src="slider/img/arrow-left.png"> VOLVER
</div>
</div>
</div>
<div class="content-inter">
<div class="container-fluid sec-title-hd-sub">
<div class="row">
<div class="col-md-7">
<div>
<figure class="img_N">
#foreach (var n in Model)
{
var img = n.Noticias2.FirstOrDefault();
if (img != null && img.Nombre.Equals(#principalId+"_0"))
{
var imgRuta = #img.Ruta+#img.Nombre+#img.Extension;
<img id="currentprincipalImagen" src="#imgRuta" class="img-responsive" alt="Imagen de Marte" />
<figcaption>
<p id="currentPrincipalImagenTitulo">#img.Descripcion</p>
</figcaption>
}
}
</figure>
</div>
<div class="textnota">
<br>
<h6 id="currentprincipalId">#principalId</h6>
<h5 id="currentprincipalTitulo" class="titulo_N uppercase">#principalTitulo</h5>
<p id="currentprincipalFechaDesde" class="time">FeDesde: #principalFechaDesde.ToString(format)</p>
<div class="noti_P">
<p id="currentprincipalContenido">#principalContenido</p>
</div>
</div>
</div>
<div class="col-md-5">
<!-- Right Side -->
#foreach (var n in Model)
{
<blockquote class="blockquote-nopadding bg-calendar-border-left">
<h6 class="IdNoticia">#n.IdNoticia</h6>
<p class="time_f feDesde">#n.FeDesde.ToString(format)</p>
#n.Titulo
<p class="text-justify limit Contenido">#n.Contenido</p>
</blockquote>
}
Págnia #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) de #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
<div>
</div>
</div>
</div>
</div>
</div>
</div>
Thanks. I know that in my Jquery Script code I dont have something to change the Image but I remove this because I cant do the relation to change the Id into the #foreach in the left side to changue my principal Image. my english is not good I hope you could understand me.
Here is the relation where If I click the first with Id = 1 I want to get the images from that Id and the same with Id = 2, 3, 4...
I found my own solution, the problem was in my Jquery code. Maybe it is not the best way to do it in Entity Framework but this is how I solve this. (If you have a better way please share it).
Here my full new code.
#{
var format = "dddd, MMMM dd, yyyy";
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutPage.cshtml";
int principalId = Model[0].IdNoticia;
string principalTitulo = Model[0].Titulo;
string principalContenido = Model[0].Contenido;
DateTime principalFechaDesde = Convert.ToDateTime(Model[0].FeDesde);
DateTime principalFechaHasta = Convert.ToDateTime(Model[0].FeHasta);
}
<script type="text/javascript">
function changeDisplay(e) {
var principalTitulo = $(e).text();
var principalContenido = $(e).siblings(".Contenido:first").val();
var principalId = $(e).siblings(".IdNoticia:first").val();
var principalFechaDesde = $(e).siblings(".FeDesde:first").val();
var principalFechaHasta = $(e).siblings(".FeHasta:first").val();
var principalDescripcion = $(e).siblings(".Descripcion:first").val();
var principalImagen = $(e).siblings(".imgRuta").val();
$("#currentprincipalTitulo").html(principalTitulo);
$("#currentprincipalContenido").html(principalContenido);
$("#currentprincipalId").html(principalId);
$("#currentprincipalFechaDesde").html(principalFechaDesde);
$("currentprincipalFechaHasta").html(principalFechaHasta);
$("#currentprincipalDescripcion").html(principalDescripcion);
$("#currentprincipalImagen").attr("src", principalImagen);
}
</script>
<!-- Principal -->
<div class="col-md-12 main">
<div class="header sec-title-hd">
<div class="bg-calendar"></div>
<div class="col-md-7">
<h5 class="pull-left">NOTICIAS</h5>
<div>
<img src="slider/img/arrow-left.png"> VOLVER
</div>
</div>
</div>
<div class="content-inter">
<div class="container-fluid sec-title-hd-sub">
<div class="row">
<div class="col-md-7">
<div>
<figure class="img_N">
#foreach (var n in Model)
{
var img = n.Noticias2.FirstOrDefault();
if (img != null && img.Nombre.Equals(#principalId+"_0"))
{
<img id="currentprincipalImagen" src="#img.Ruta#img.Nombre#img.Extension" class="img-responsive" alt="#img.Nombre" />
<figcaption>
<p id="currentprincipalDescripcion">#img.Descripcion</p>
</figcaption>
}
}
</figure>
</div>
<div class="textnota">
<br>
<h6 id="currentprincipalId">#principalId</h6>
<h5 id="currentprincipalTitulo" class="titulo_N uppercase">#principalTitulo</h5>
<p id="currentprincipalFechaDesde" class="time">Desde: #principalFechaDesde.ToString(format)</p>
<p id="currentprincipalFechaHasta" class="time">Hasta: #principalFechaHasta.ToString(format)</p>
<div class="noti_P">
<p id="currentprincipalContenido">#principalContenido</p>
</div>
</div>
</div>
<div class="col-md-5">
<!-- Right Side -->
#foreach (var n in Model)
{
<!-- Data mostrada -->
<blockquote class="blockquote-nopadding bg-calendar-border-left">
<p class="time_f">#n.FeDesde.ToString(format)</p>
#n.Titulo
<p class="text-justify limit">#n.Contenido</p>
<!--Data Enviada al lado Izquierdo-->
<input class="IdNoticia" type="hidden" value="#n.IdNoticia" />
<input class="Contenido" type="hidden" value="#n.Contenido" />
<input class="FeDesde" type="hidden" value="Desde: #n.FeDesde.ToString(format)" />
<input class="FeHasta" type="hidden" value="Hasta: #n.FeHasta.ToString(format)" />
#foreach (var img in n.Noticias2)
{
var imgRuta = #img.Ruta + #img.Nombre + #img.Extension;
<input class="Descripcion" type="hidden" value="#img.Descripcion" />
<input class="imgRuta" type="hidden" value="#imgRuta" />
}
</blockquote>
}
</div>
</div>
</div>
</div>
Here the new view,
notice that all the data in the left side are from the id 2.

Search data on click event of button using smart table

I am very new to the smart table. I have gone through its documentation on Smart Table.
But the I haven't found how to bind data on click event in smart table?
Code is very big but I am trying to post it here.
<div class="table-scroll-x" st-table="backlinksData" st-safe-src="backlinks" st-set-filter="myStrictFilter">
<div class="crawlhealthshowcontent">
<div class="crawlhealthshowcontent-right">
<input type="text" class="crserachinput" placeholder="My URL" st-search="{{TargetUrl}}" />
<a class="bluebtn">Search</a>
</div>
<div class="clearfix"></div>
</div>
<br />
<div class="table-header clearfix">
<div class="row">
<div class="col-sm-6_5">
<div st-sort="SourceUrl" st-skip-natural="true">
Page URL
</div>
</div>
<div class="col-sm-2">
<div st-sort="SourceAnchor" st-skip-natural="true">
Anchor Text
</div>
</div>
<div class="col-sm-1">
<div st-sort="ExternalLinksCount" st-skip-natural="true">
External<br />Links
</div>
</div>
<div class="col-sm-1">
<div st-sort="InternalLinksCount" st-skip-natural="true">
Internal<br />Links
</div>
</div>
<div class="col-sm-1">
<div st-sort="IsFollow" st-skip-natural="true">
Type
</div>
</div>
</div>
</div>
<div class="table-body clearfix">
<div class="row" ng-repeat="backlink in backlinksData" ng-if="backlinks.length > 0">
<div class="col-sm-6_5">
<div class="pos-rel">
<span class="display-inline wrapWord" tool-tip="{{ backlink.SourceUrl }}"><b>Backlink source:</b> <a target="_blank" href="{{backlink.SourceUrl}}">{{ backlink.SourceUrl }}</a></span><br />
<span class="display-inline wrapWord" tool-tip="{{ backlink.SourceTitle }}"><b>Link description:</b> {{ backlink.SourceTitle }}</span> <br />
<span class="display-inline wrapWord" tool-tip="{{ backlink.TargetUrl }}"><b>My URL:</b> <a target="_blank" href="{{backlink.TargetUrl}}">{{ backlink.TargetUrl }}</a></span><br />
</div>
</div>
<div class="col-sm-2">
<div class="pos-rel">
{{ backlink.SourceAnchor }}
</div>
</div>
<div class="col-sm-1">
<div>
{{ backlink.ExternalLinksCount }}
</div>
</div>
<div class="col-sm-1">
<div>
{{ backlink.InternalLinksCount }}
</div>
</div>
<div class="col-sm-1">
<div ng-if="!backlink.IsFollow">
No Follow
</div>
</div>
</div>
<div class="row" ng-if="backlinks.length == 0">
No backlinks exists for selected location.
</div>
</div>
<div class="pos-rel" st-pagination="" st-displayed-pages="10" st-template="Home/PaginationCustom"></div>
</div>
and my js code is here.
module.controller('backlinksController', [
'$scope','$filter', 'mcatSharedDataService', 'globalVariables', 'backlinksService',
function ($scope,$filter, mcatSharedDataService, globalVariables, backlinksService) {
$scope.dataExistsValues = globalVariables.dataExistsValues;
var initialize = function () {
$scope.backlinks = undefined;
$scope.sortOrderAsc = true;
$scope.sortColumnIndex = 0;
};
initialize();
$scope.itemsByPage = 5;
var updateTableStartPage = function () {
// clear table before loading
$scope.backlinks = [];
// end clear table before loading
updateTableData();
};
var updateTableData = function () {
var property = mcatSharedDataService.PropertyDetails();
if (property == undefined || property.Primary == null || property.Primary == undefined || property.Primary.PropertyId <= 0) {
return;
}
var params = {
PropertyId: property.Primary.PropertyId
};
var backLinksDataPromise = backlinksService.getBackLinksData($scope, params);
$scope.Loading = backLinksDataPromise;
};
mcatSharedDataService.subscribeCustomerLocationsChanged($scope, updateTableStartPage);
}
]);
module.filter('myStrictFilter', function ($filter) {
return function (input, predicate) {
return $filter('filter')(input, predicate, true);
}
});
But It is working fine with the direct search on textbox.
but according to the requirement I have to perform it on button click.
Your suggestions and help would be appreciated.
Thanks in advance.
You can search for a specific row by making some simple tweaks.
add a filter to the ng-repeat, and filter it by a model that you will insert on the button click, like so: <tr ng-repeat="row in rowCollection | filter: searchQuery">
in your view, add that model (using ng-model) to an input tag and define it in your controller
then pass the value to the filter when you click the search button
here's a plunk that demonstrates this
you can use filter:searchQuery:true for strict search
EDIT:
OK, so OP's big problem was that the filtered values wouldn't show properly when paginated, the filter query is taken from an input box rather then using the de-facto st-search plug-in, So I referred to an already existing issue in github (similar), I've pulled out this plunk and modified it slightly to fit the questioned use case.

Categories