I have a table
I have constructed these rows and action buttons dynamically as soon as user clicked on Devices accordion.
When the user clicks on the (I)
<i class="fa fa-info ml15"></i>
It should called expandCollapseCurrent() function. Somehow it never reaches there, and there is nothing in the console for me to understand why it didn’t reach
$scope.expandCollapseCurrent = function(currentDevice) {
console.log('%c currentDevice = ' + currentDevice, "color: green;");
angular.forEach($scope.private_devices, function(device) {
if(device.name != currentDevice.name) {
device.settingsEnabled = false;
device.viewEnabled = false;
}
$scope.buttonShow.bandwidth = false;
$scope.buttonShow.acl = false;
});
}
It never did.
This is my entire code for that.
$('#wifi-devices-nav').click( function() {
if($('#wifi-devices-nav').hasClass('callout-expanded')) {
$.ajax({
method: 'GET',
url: '/api/telenet/' + '{{ $cpe_mac }}' + '/privateDevices',
crossDomain: true,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('value'),
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
success: function(response){
$('.lds-ripple').fadeOut();
console.log(response.length);
for (i = 0; i < response.length; i++) {
var device = response[i];
if(device.up) {
console.log(device);
}
if(device.device_activity != "OFFLINE" && device.device_activity_v6 != "OFFLINE" ) {
console.log(response[i]);
if(device.up) {
var uplink = device.up.value + ' ' + device.up.suffix;
}
if(device.down) {
var downlink = device.down.value + ' ' + device.up.suffix;
}
if(device.device_activity == 'ACTIVE') {
var deviceStatus = 'green';
}else {
var deviceStatus = 'orange';
}
let row = `
<tr id="tr-${device.device_mac}">
<td>
{{-- Status --}}
<i class="device-status-circle fa fa-circle ${deviceStatus}" style="margin-left:7px; ">
</i>
${device.device_mac}
</td>
<td class="text-center">${device.ip_address_v6}</td>
<td class="text-center">${device.last_active} </td>
<td class="text-center">
<!-- View -->
<i class="fa fa-info ml15"></i>
<!-- Edit -->
<i class="fa fa-pencil ml15"></i>
<!-- Settings -->
<i class="fa fa-cog ml15"></i>
</td>
</tr>
`;
$('#tablePrivateDevices').prepend(row).fadeIn('slow');
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
});
Updated Observations
Any of the 3 buttons that I clicked, will refresh the page.
I have NO idea why it does that ...
Any hints/suggestions will mean a lot to me.
You can not just add html like <button ng-click="... you need to $compile it first. As you do not, directive is ignored and you get default browser behaviour - it follows href.
P.S. This mixture of jquery and angularjs looks pretty akward...
Related
I have method who populate menu, it be like:
function MenuPopulate(url, listname, target) {
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
$(function () {
$.ajax({
url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang ,
async: false,
type: 'GET',
dataType: "json",
success: function (data) {
console.log(data);
completeMenu(data, target)
//localStorage.setItem('data', JSON.stringify(data))
},
error: function (response) {
failureMenu(response, target)
}
});
});
}
function completeMenu(data, target) {
var prefix = "<ul class='nav navbar-nav navbar-right'>";
var sufix = "</ul>";
var items = data;
var menu = "";
for (item in items) {
if(items[item].Titile == "JOIN US" ){
menu += "<li><a href='#mymodal' data-toggle='modal' data-target='#mymodal'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
}
else if(items[item].Titile == "CONTACT US"){
menu += "<li><a href='#mymodal2' data-toggle='modal' data-target='#mymodal2'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
}
else{
menu += "<li>" + items[item].Titile + "</li><li class='divider-vertical'></li>";
}
}
$(target).html(prefix + menu + sufix);
}
function failureMenu(data, target) {
console.log(data);
$(target).text("Ocurrió un error en la carga del menú. Por favor revise la consola para más información");
}
And it runs perfectly except for the time to load page, so now I store methods in cache with localStorage , so I made this class:
$(document).ready(function() {
GetGlobal();
});
function GetGlobal() {
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
var page = window.location.pathname.replace("/SitePages/", "");
if (localStorage.getItem("Menu") == null) {
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
//alert("Cargo con exito");
},
error: function(data) {
//failureGlobal(data);
alert("No cargo");
}
})
} else {
// alert("la cookie esta cargada");
CargaGlobal();
//localStorage.getItem("Menu")
}
}
function CargaMenu() {
$.ajax({
url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang,
async: false,
cache:true,
type: 'GET',
dataType: "json",
success: function(data) {
console.log(data);
completeMenu(data, target)
},
error: function(response) {
failureMenu(response, target)
}
});
}
function CompleteGlobal(data) {
data.Menu //lista de menus
data.Pie // lista pie de pagina
data.Mapa
data.Ligas
localStorage.setItem("Menu", JSON.stringify(data.Menu));
localStorage.setItem("Pie", JSON.stringify(data.Pie));
localStorage.setItem("Mapa", JSON.stringify(data.Mapa));
localStorage.setItem("Ligas", JSON.stringify(data.Ligas));
localStorage.setItem("Enlace", JSON.stringify(data.Enlace));
CargaGlobal();
}
function CargaGlobal() {
completeMenu(JSON.parse(localStorage.getItem("Menu")), "#BarraNavegacion");
completeSiteMap(JSON.parse(localStorage.getItem("Mapa")), "#MapaSitio");
completeImgLinks(JSON.parse(localStorage.getItem("Enlace")), "#EnlacesImagen");
completeFooter(JSON.parse(localStorage.getItem("Pie")), "#Footer");
}
function completeBanner3(target) {
var items = localStorage.getItem("Menu");
var menu = "";
for (var item in items) {
menu += "<div class='col-md-4 text-center'><div><a href='" + items[item].Enlace + "'><img src='" + items[item].Imagen + "' class='img-responsive img-center' /></a></div><div class='t02 text-center'>" + items[item].Titulo + "</div><div class='t03 text-center'>" + items[item].Descripcion + "</div></div>";
}
$(target).html(menu);
}
But when I change language of my site it just no load the other language menu, and I think to load cookie again if language is different to "Espanol" so I think I can do something like
if (localStorage.getItem("Menu") == null && lang == "Espanol") {
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
//alert("Cargo con exito");
}else if(localStorage.getItem("Menu") == null && lang == "English"){
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
},
error: function(data) {
alert("No cargo");
}
})
} else {
CargaGlobal();
}
}
But it doesn´t works, any idea what I need to do in this case? Regards
Instead of saving individual parts to the localStorage, sometimes it's easier just to get and fetch an object by using JSON.parse and JSON.stringify.
This is a rather long example, but I commented it a lot to try to make it easier to follow. It's an illustration of various concepts so it doesn't exactly solve your problem, but I believe it will get you closer to a solution.
EDIT: The StackOverflow script runner does not like localStorage. Here's a JSFiddle to see it in action: https://jsfiddle.net/subterrane/9prr5ks6/
EDIT, EDIT: Also, I don't speak Spanish, so blame Google Translate for the silly menu button labels.
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
// function to getMenuData
function getMenuData() {
// get the saved data from localStorage
var menuData = JSON.parse(localStorage.getItem('menuData'));
// if it doesn't exist, or if our language is missing, fetch the data from the server
if (menuData == null || menuData[lang] == null) {
// this is a stub function. Pretend it's doing an ajax request
// the second argument here is a callback function. It would be
// the ajax success function.
fetchMenuData(lang, function(data) {
// if we did have some of the data, use it, or start with an empty object
menuData = menuData || {};
// set the server response to the menuData object
menuData[lang] = data;
// stringify the object and stash it in localStorage
localStorage.setItem('menuData', JSON.stringify(menuData));
// display the menu
displayMenu(menuData);
});
} else {
// we go the data from the cache, so display the menu
displayMenu(menuData);
}
}
// this is a fake function that pretends to get menuData from a server
function fetchMenuData(lang, callback) {
// wait 2 seconds, then call the response function
setTimeout(response, 2000);
// response function sends some data back to the callback depending on the requested language
function response() {
callback(lang == "Espanol" ? [{
name: 'Casa',
link: 'something.html'
}, {
name: 'Lejos',
link: 'somethingelse.html'
}] : [{
name: 'Home',
link: 'something.html'
}, {
name: 'Away',
link: 'somethingelse.html'
}]);
}
}
// function to display the menu
function displayMenu(data) {
// update the text in some of the buttons
document.getElementById('home').innerHTML = data[lang][0].name;
document.getElementById('away').innerHTML = data[lang][1].name;
// looks kinda funny, but this just puts the opposite of the current language
// on the button to make it feel like a toggle button
document.getElementById('toggle').innerHTML = lang == "Espanol" ? "English" : "Espanol";
// show the menu now that it's filled in
document.getElementById('menu').classList.remove('hide');
}
// set up a click handler on the language toggle button
document.getElementById('toggle').addEventListener('click', function() {
// hide the menu while we mess with it. Could take a while to get the menu
// data back from our 'server'
document.getElementById('menu').classList.add('hide');
// set the language to the opposite of whatever it was before
lang = lang == "Espanol" ? "English" : "Espanol";
// get the menu data from the cache or server
getMenuData();
});
// kick it all off by getting the menu data from the server
getMenuData();
.hide {
display: none;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
<div id="menu" class="hide">
<button id="home"></button>
<button id="away"></button>
<button id="toggle"></button>
</div>
</div>
My code have a button that can print a file to a pdf form (it works fine). Now I want to add another button that just print it in a html page. I have added the new button and it works too.
The problem is that now when I have created a new button, it will now overwrite it method on the old one. So both button will do the same thing. (Both print it in html form)
Here are some part of my code:
The function for the invoice datatable looks like this:
function invoiceDatatable(tableId, extras, url, optionParser) {
var options = $.extend(true, {}, documentOptions, {
tableId: tableId,
url: url || '/api/invoices/?type=i',
extras: extras
});
Here i create both buttons, with their url - the code always use the last created one:
options.tasks.push({
url: '/print_to_pdf',
queryParam: 'documents',
label: '<i class="fa fa-print"></i> Print pdf'
});
options.tasks.push({
url: '/print_to_html',
queryParam: 'documents',
label: '<i class="fa fa-print"></i> Print html'
});
Finally the code for the tasks of the buttons looks like this:
for (var i = 0; i < self.tasks.length; i++) {
var task = self.tasks[i];
var taskButton = $('<button type="button">' + (task.label || task) + '</button>');
taskButton.addClass('btn btn-default');
$(taskButtons).append(taskButton);
if (task.action) {
// An entry point for custom actions
$(taskButton).click(function(){
task.action(self.selected);
})
} else {
$(taskButton).click(function () {
var downloadUrl = task.url + '?' + task.queryParam + '=' + self.selected.join(',');
downloadUrl += "&ordering=" + self.ordering()['ordering'];
$(infoPanel + ' .alert').remove();
$(infoPanel).append('<div class="alert alert-info">' +
'<i class="fa fa-circle-o-notch fa-spin"></i> Building document' +
'</div>');
$.ajax(downloadUrl, {
success: function (data) {
function doPoll(url, success) {
$.ajax(jobUrl, {
type: "HEAD",
success: function (pdfData, status, xhr) {
if (xhr.status == 202) {
setTimeout(function () {
doPoll(url, success)
}, 2000);
} else {
success()
}
}
});
$.ajax(url, function (data) {
alert(data); // process results here
setTimeout(doPoll, 5000);
});
}
How do I fix my code so that each button have its own functionality?
edit
I think it is the push method that overwrites the action. What do you guys think?
So basically I have a button on my html which has a small js on it which onclick turns the button green and when clicked again turns the button grey to make it feel like its turning on and off. Here is the JS and the HTML code for the button
<script>
$('#button1').click(function() {
//Now just reference this button and change CSS
$(this).toggleClass('buttonClassA');
});
</script>
<button type="button" class="col-md-2 notice-btns btn " id="button1">
<span class="glyphicon glyphicon-phone" aria-hidden="true"></span>
<p data-bind="if : $data.emailNotification == 1 ">On</p>
<p data-bind="if : $data.emailNotification == 0 ">Off</p>
</button>
I have two knockout function which needs to be called when the button is clicked
which are
self.emailNotification = ko.observable();
self.turnOnEmailNotification = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationValue/' + auth + "/" + self.emailNotification(1) ,
contentType: 'application/json; charset=utf-8'
})
.done(function(notifications) {
self.emailNotification.removeAll();
self.emailNotification.push(notifications);
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.turnOffEmailNotification = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationValue/' + auth + "/" + self.emailNotification(0) ,
contentType: 'application/json; charset=utf-8'
})
.done(function(notifications) {
self.emailNotification.removeAll();
self.emailNotification.push(notifications);
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
I tried the data-bind checked but then i lose the buttons so need help to call both the ajax calls
$root.turnOnEmailNotification
and
$root.turnOffEmailNotification
in the same button and so I can give it a feeling its turning on and off.
Checked isn't a valid attribute for button element .Instead you can use click to achieve the same via toggling .
view:
<button type="button" data-bind="click:tgle,style:{'background-color':emailNotification()==0 ? 'red':'green'}">
<p data-bind="text:$data.emailNotification() == 1 ? 'On' : 'Off' "></p>
</button>
viewModel:
var ViewModel = function() {
var self = this;
self.emailNotification = ko.observable(0);
self.tgle = function() {
self.emailNotification(self.emailNotification() == 1 ? 0 : 1)
switch (self.emailNotification()) {
case 0:
console.log('turn off ajax fired');
//turnOFFEmailNotification
//$.ajax({
// Do ajax stuff
//});
break;
case 1:
console.log('turn on ajax fired');
//turnOnEmailNotification //default off
//$.ajax({
// Do ajax stuff
//});
break;
default:
break;
}
}
};
ko.applyBindings(new ViewModel());
working sample up for grabs
This is how my webpage looks like:
As can be seen in the picture I have I have search on the top right, in the bottom right I have the amount of pages etc..
But as I add another project here by clicking "Lägg till ny" and add a project for some reason my page will end up like this:
http://puu.sh/kKSZz/387c71f487.png
As can be seen the table "Breaks" the search field gets removed and so does the pages. Same things happens when I chose to edit or delete a project I've already added.
This is my view:
<div id="tabs-current">
<div id="ConsultantTimes">
#{
Html.RenderAction("ConsulantTimes");
}
</div>
<a href="javascript:OpenDialog()" class="btn btn-primary">
Lägg till ny
</a>
</div>
As can be seen the table is a partial view and here it is:
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>Projekt</th>
<th>Mitt Datum</th>
<th>%</th>
<th>Projektdatum</th>
</tr>
</thead>
<tbody>
#foreach (var project in ViewData["times"] as List<ConsultantProjectTime>)
{
<tr>
<td>
<a href="javascript:OpenDialog2('#project.ID','#project.FK_ProjectID','#project.StartDate.ToShortDateString()','#project.EndDate.ToShortDateString()','#project.Pct');">
#project.Project.ProjectName
</a>
</td>
<td>#(project.StartDate.ToShortDateString() + " - " + project.EndDate.ToShortDateString())</td>
<td>#(project.Pct)%</td>
<td>
#if (project.Project.StartDate.HasValue && project.Project.EndDate.HasValue)
{
#(project.Project.StartDate.Value.ToShortDateString() + " - " + project.Project.EndDate.Value.ToShortDateString())
}
</td>
</tr>
}
</tbody>
And this is my script I run when I choose to add another project:
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 220,
width: 305,
modal: true,
buttons: {
'Spara': function() {
if (!validate()) {
alert('Procent måste vara mellan 0-100');
return false;
}
locstring = "#(Url.Action("Index"))/Update/?";
locstring += '&projectId=' + $('#projectList').val();
locstring += '&startDate=' + $('#startDate').val();
locstring += '&endDate=' + $('#endDate').val();
locstring += '&pct=' + $('#pct').val();
var sid = $('#sId').text();
if (sid != "") {
locstring += '&id=' + sid;
//locstring = "/Delete/" + sid;
}
//window.location = locstring;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
//alert(locstring);
$('#dialog').dialog('close');
ReloadTable();
}
});
},
'Avbryt': function() {
$(this).dialog('close');
},
'Ta bort': function() {
var sid = $('#sId').text();
if (sid != "") {
locstring = "#(Url.Action("Index"))/Delete/" + sid;
//locstring += '&delete=true&id=' + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
ReloadTable();
}
});
Note, when this happends I have no errors in my console.
Found the error but not sure how to solve it, it's my ReloadTable function:
function ReloadTable() {
if (navigator.appName == "Microsoft Internet Explorer") {
//alert('suck..');
window.location.reload();
} else {
$.ajax({
type: "GET",
url: '#(Url.Action("ConsulantTimes"))',
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
$('#ConsultantTimes').html(data);
}
});
}
}
What you are doing is replacing the entire contents of #ConsultantTimes and replacing it with the data variable. Use $( "sample_1" ).replaceWith(data); instead, or maybe prepend or append.
I'm trying to remove my entry to my table but when I press the remove button nothing happends, I know it goes into the remove method as it hits my Alert I did set there.
This is my Script to open a dialog:
function OpenDialog2(id, projectId, startDate, endDate, pct) {
ClearDialog();
$('#projectList').val(projectId);
$('#startDate').val(startDate);
$('#endDate').val(endDate);
$('#pct').val(pct);
$('#sId').text(id);
$('#dialog').dialog('open');
}
This is my method trying to remove it:
'Ta bort': function () {
alert("Ta bort");
var sid = $('#sId').text();
if (sid !== "") {
locstring = "#Url.Action("Index")/Delete/" + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function (data) {
$('#dialog').dialog('close');
reloadTable();
}
});
}
This is my Partial View:
#foreach (var project in ViewData["times"] as List<ConsultantProjectTime>)
{
<tr>
<td>
<a href="javascript:OpenDialog2('#project.ID','#project.FK_ProjectID','#project.StartDate.ToShortDateString()','#project.EndDate.ToShortDateString()','#project.Pct');">
#project.Project.ProjectName
</a>
</td>
<td>#(project.StartDate.ToShortDateString() + " - " + project.EndDate.ToShortDateString())</td>
<td>#(project.Pct)%</td>
<td>
#if (project.Project.StartDate.HasValue && project.Project.EndDate.HasValue)
{
#(project.Project.StartDate.Value.ToShortDateString() + " - " + project.Project.EndDate.Value.ToShortDateString())
}
</td>
</tr>
}