How to grab specific JSON entry using AngularJS - javascript

Here's a picture of the current output:
output image
I'm trying to have it show the active title when you click download, and not every entry.
I'm also trying to have it show the download file(s) name instead of static text, or the URL.
The JS code that loads the titles is:
(function($){
var titledbApp = angular.module('dsshop', ['angular-loading-bar'])
.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
cfpLoadingBarProvider.includeSpinner = false;
cfpLoadingBarProvider.parentSelector = '#loading-bar-container';
}]);
titledbApp.controller('TitleListController', function TitleListController($scope, $http) {
$http.get('https://nitrobrew.github.io/BrewShopNitro/list0.json').then(function(response){
$scope.titles = response.data.sort(function(a, b){
if(a.name.toUpperCase() < b.name.toUpperCase()) return -1;
if(a.name.toUpperCase() > b.name.toUpperCase()) return 1;
return 0;
});
});
});
//Filesize filter, credit to https://gist.github.com/yrezgui/5653591
titledbApp.filter( 'filesize', function () {
var units = [
'bytes',
'KB',
'MB',
'GB',
'TB',
'PB'
];
return function( bytes, precision ) {
if ( isNaN( parseFloat( bytes )) || ! isFinite( bytes ) ) {
return '?';
}
var unit = 0;
while ( bytes >= 1024 ) {
bytes /= 1024;
unit ++;
}
return bytes.toFixed( + precision ) + ' ' + units[ unit ];
};
});
})();
The HTML code that loads the modal box (bootstrap modal) is:
<div class="modal fade" id="downloadModal" tabindex="-1" role="dialog" aria-labelledby="downloadModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel" ng-repeat="title in titles">
<center>{{title.name}} download menu</center>
</h4>
</div>
<div class="modal-body">
<a ng-href="{{title.files[0].url}}" title="{{title.files[0].url}}"
ng-repeat="title in titles">File 1</a>
<br>
{{title.files[1]}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-blue" data-dismiss="modal"
data-toggle="tooltip">Cancel</button>
</div>
</div>
</div>
</div>
Any help is greatly appreciated!

Related

Getting button Id and passing id to a model button id

I have a dynamic button, that has an attribute of Stepid. What i am trying to do
is capture that attribute when the button is clicked and pass the same attribute into my model and assign the StepId value as my button Id in the modal.
My button
<button class="btn btn-warning moveRecipeStep" id="blah" data-bind="attr: {'data-id': StepId, data_recipe_name: $parent.RecipeName}" data-toggle="modal" data-target="#moveRecipeReason">#Html.LocalisedStringFor(model => model.MoveToStageText)</button>
and my modal
<section id="hidden">
<div class="modal fade" id="moveReason" tabindex="-1" role="dialog" arial-labelledby="moveReasonLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="moveReasonLabel">What is the reason for the Step move?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body reasonDialog">
<form>
<div class="form-group">
#Html.LabelFor(model => model.ReasonText)
#Html.TextAreaFor(model => model.ReasonText, new { rows = 4, #class = "form-control", maxlength = "100", data_bind = "value: Reason" })
</div>
</form>
</div>
<div class="modal-footer">
<button id="DoMove" type="button" class="btn btn-primary">#Html.LocalisedStringFor(model => model.SubmitText)</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="moveRecipeReason" tabindex="-1" role="dialog" arial-labelledby="moveReasonLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="moveReasonLabel">What is the reason for the Recipe move?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body reasonDialog">
<form>
<div class="form-group">
#Html.LabelFor(model => model.ReasonText)
#Html.TextAreaFor(model => model.ReasonText, new { rows = 4, #class = "form-control", maxlength = "100", data_bind = "value: Reason" , id = "blah" })
</div>
</form>
</div>
<div class="modal-footer">
<button id="DoMoveRecipe" type="button" class="btn btn-primary">#Html.LocalisedStringFor(model => model.SubmitText)</button>
</div>
</div>
</div>
</div>
</section>
And my javascript
var input = $(this);
var buttonId = input.attr("id");
var id = input.data("id");
var url = buttonId === 'MoveNext' ? '#Url.Action("MakeNext")' : '#Url.Action("MoveRecipePosition")';
$("#moveReason").modal("toggle");
if (buttonId === "MoveNext") {
$.ajax(url,
{
data: {
"Id": id,
"Reason": $("#moveReason .reasonDialog textarea").val(),
},
cache: false,
method: "POST",
}).done(function(returnData) {
if (returnData) {
if (returnData.BrokenRule !== null) {
alert(returnData.BrokenRule.Message);
} else if (returnData.ProcessStep !== null) {
var bFound = false;
//Done like this because you can only move backwards. Originally the logic was fuller but, most things don't change now.
//The extra logic just hides everything past the active one
for (var pos = 0; pos < viewModel.Stages().length; pos++) {
if (bFound) {
viewModel.Stages()[pos].Id(-1);
viewModel.Stages()[pos].IsNext(false);
} else if (viewModel.Stages()[pos].Id() == returnData.ProcessStep.Id) {
viewModel.Stages()[pos].IsNext(returnData.ProcessStep.IsNext);
viewModel.Stages()[pos].BenchId(returnData.ProcessStep.BenchId);
viewModel.Stages()[pos].BenchName(returnData.ProcessStep.BenchName);
viewModel.Stages()[pos].IsTransacted(returnData.ProcessStep.IsTransacted);
viewModel.Stages()[pos].RecipeName(returnData.ProcessStep.RecipeName);
bFound = true;
}
}
}
}
}).fail(function(xhr) {
try {
console.log(xhr.statusText);
console.log(xhr.responseText);
alert(xhr.statusText + "\r\n" + xhr.responseText);
} catch (ex) {
console.log(ex);
alert(ex);
}
});
} else {
$.ajax(url,
{
data: {
"SerialNumber": viewModel.SerialNumber(),
"Message": $("#moveRecipeReason .reasonDialog textarea").val(),
"StepId": a
},
cache: false,
method: "POST"
}).done(function(returnData) {
if (returnData) {
if (returnData.BrokenRule !== null) {
alert(returnData.BrokenRule.Message);
} else if (returnData.recipePosition !== null) {
var bFound = false;
//Done like this because you can only move backwards. Originally the logic was fuller but, most things don't change now.
//The extra logic just hides everything past the active one
for (var pos = 0; pos < viewModel.Stages().length; pos++) {
if (viewModel.Stages()[pos].RecipeName() !==
returnData.recipePosition.RecipeName)
continue;
for (var innerPos = 0;
innerPos < viewModel.Stages()[pos].RecipeStages().length;
innerPos++) {
var recipeStage = viewModel.Stages()[pos].RecipeStages()[innerPos];
if (bFound) {
recipeStage.StepId(-1);
recipeStage.IsNext(false);
} else if (viewModel.Stages()[pos].Id() === returnData.ProcessStep.Id) {
recipeStage.StepId(-1);
recipeStage.IsNext(true);
bFound = true;
}
}
}
}
}
}).fail(function(xhr) {
try {
console.log(xhr.statusText);
console.log(xhr.responseText);
alert(xhr.statusText + "\r\n" + xhr.responseText);
} catch (ex) {
console.log(ex);
alert(ex);
}
});
}
})
});
If anyone can give me some guidance, that much be much appreciated. Thank you very much.
It can be done simpler, here's an universal concept: How do you handle multiple submit buttons in ASP.NET MVC Framework?
Simple approach:
multiple submit button, same name (let it be abcd), different value
inside .NET controllers postback function have a string name (so string abcd) input parameter, where you check the value

SyntaxError: Unexpected identifier 'modal_html'. Expected a ':'

SyntaxError: Unexpected identifier 'modal_html'. Expected a ':'
following the property name 'var'. (anonymous function) — modal.self-
Helpers = window.Helpers || {}
Helpers.Bootstrap = Helpers.Bootstrap || {}
Helpers.Bootstrap.Modal = {
var modal_html = `
<div class="modal fade" id="AlertModal" tabindex="-1" role="dialog" aria-labelledby="AlertModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AlertModalLabel">${title}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
${message}
</div>
<div class="modal-footer">
${ button_html( button1 )}
${ button_html( button2 )}
</div>
</div>
</div>
`;
init(title, message, button1, button2, existingelementid) {
if (b === undefined) {
Helpers.Bootstrap.Modal.closee(existingelementid)
}
modal_html
}
close(elementid) {
$( elementid + " .close").click();
}
button_html(button_name) {
var button_cancel = "<button type="button" class="btn btn-outline-danger" data-dismiss="modal">Cancel</button>";
var button_save = "<button type="submit" class="btn btn-outline-primary spinner" >Save</button>";
var button_ok = "<button type="button" class="btn btn-outline-primary" data-dismiss="modal">Ok</button>";
var button_close = "<button type="button" class="btn btn-outline-primary" data-dismiss="modal">Close</button>";
switch(button_name) {
case "cancel":
button_cancel;
break;
case "save":
button_save;
break;
case "ok":
button_ok;
break;
case "close":
button_close;
break;
default:
button_name;
}
}
}
You are doing a lot of things wrong here:
End your assignments Helpers = window.Helpers || {} and Helpers.Bootstrap = Helpers.Bootstrap || {} with semicolons ; (just because!)
I think Helpers.Bootstrap.Modal.closee(existingelementid) should be .close not .closee
Your html in modal_html is missing a closing </div> tag in the end
you cant decalare a var inside a object like you did with var XXX = something;
insted you just do: XXX : something, <-- (note the , in the end)
in your function init it just randomly says modal_html in the end (without assignment or anything else)
the whole code in button_html is just utter gibberish...ofc var button_cancel = "<button type=" is not a real assignment and continuing with
button " class=" will just break everything!
---> YOU CAN'T USE " to delimiter inside of ""
You are never returning anything from your switch, (atleast thats what I think you want to do)
there is alot more, but I suggest fixing this first, and maybe your original error will dissapear magically ;)
Helpers = window.Helpers || {}; /* <------ */
Helpers.Bootstrap = Helpers.Bootstrap || {}; /* <------- */
Helpers.Bootstrap.Modal = {
modal_html : `
<div class="modal fade" id="AlertModal" tabindex="-1" role="dialog" aria-labelledby="AlertModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AlertModalLabel"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div> <!-- <--------- -->
`,
button_html(button_name) {
/*
var button_cancel = "<button type="
button " class="
btn btn - outline - danger " data-dismiss="
modal ">Cancel</button>";
var button_save = "<button type="
submit " class="
btn btn - outline - primary spinner " >Save</button>";
var button_ok = "<button type="
button " class="
btn btn - outline - primary " data-dismiss="
modal ">Ok</button>";
var button_close = "<button type="
button " class="
btn btn - outline - primary " data-dismiss="
modal ">Close</button>";
switch (button_name) {
case "cancel":
button_cancel;
break;
case "save":
button_save;
break;
case "ok":
button_ok;
break;
case "close":
button_close;
break;
default:
button_name;
}
THE ABOVE CODE IN THIS COMMENT IS ALL GIBBERISH AND IS NOT CORRECT */
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Can't load 2 different modal forms with JQuery Trigger

I have some modal forms to complete some fields, in this case I have 2 modal forms, 1 for Jury and 1 for Contact, when I press 'Add' link, in both cases works fine, but the problem is when I want to edit contact.
When I press Edit in both cases I call controller to complete the Java form and then, return to view and simulate a click in "Add" button with JQuery. In jury case works fine, but in Contact I only get a dark screen (like if modal works), but modal window never appear. Other problem is, when I press Edit button in Jury and then close the jury modal form, when I press Edit in Contact it launch the jury modal form...
Contact Modal and Add link (Edit link doesn't works)
<div class="row margin-top-10">
<div class="col-xs-2 col-md-2 col-md-push-10">
<a id="btnAddCForm" href="#modal-cForm-form" data-toggle="modal" class="btn fpa btn-block pull-right">AÑADIR NUEVO</a>
</div>
</div>
<div id="modal-cForm-form" class="modal fade" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Nuevo/Editar Forma de contacto</h4>
</div>
<div class="modal-body">
<div class="scroller" style="height:390px" data-always-visible="1" data-rail-visible1="1">
Some fields
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn default">CANCELAR</button>
<button type="button" onclick="addContactForm();" class="btn fpa">ACEPTAR</button>
</div>
</div>
</div>
</div>
Jury Modal and Add link (Works fine)
<div class="row margin-top-10">
<div class="col-xs-2 col-md-2 col-md-push-10">
<a id="btnAddJurado" href="#modal-jury-form" data-toggle="modal" class="btn fpa btn-block pull-right">AÑADIR NUEVO</a>
</div>
</div>
<div id="modal-jury-form" class="modal fade" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" onclick="resetValues();"></button>
<h4 class="modal-title">Nuevo/Editar Jurado</h4>
</div>
<div class="modal-body">
<div class="scroller" style="height:300px" data-always-visible="1" data-rail-visible1="1">
Some Fields
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" onclick="resetValues();" class="btn default">CANCELAR</button>
<button type="button" onclick="addJury();" class="btn fpa">ACEPTAR</button>
</div>
</div>
</div>
</div>
Onload (In main html document)
window.onload = function () {
/*<![CDATA[*/
var idJuryAux = /*[[${person.juryAux.id}]]*/
null;
var idContactFormAux = /*[[${person.contactFormAux.id}]]*/
null;
/*]]>*/
var idProvincia = $('#provinceField').val();
var idPais = $('#countryField').val();
if (idPais == '-1') {
$('#provinceField').attr("readonly", true);
} else {
$('#provinceField').attr("readonly", false);
}
if (idProvincia == '-1') {
$('#cityField').attr("readonly", true);
} else {
$('#cityField').attr("readonly", false);
}
if (idJuryAux != null) {
/*<![CDATA[*/
var idCat = /*[[${person.juryAux.category}]]*/
null;
var idCargo = /*[[${person.juryAux.juryType}]]*/
null;
var catName = /*[[${person.juryAux.categoryName}]]*/
null;
var cargoName = /*[[${person.juryAux.juryTypeName}]]*/
null;
/*]]>*/
$('#btnAddJurado').trigger('click');
$("#categoryField").select2('data', {
id: idCat,
text: catName
});
$("#juryTypeField").select2('data', {
id: idCargo,
text: cargoName
});
}
if (idContactFormAux != null) {
/*<![CDATA[*/
var idType = /*[[${person.contactFormAux.type}]]*/
null;
var typeName = /*[[${person.contactFormAux.typeName}]]*/
null;
var idTag = /*[[${person.contactFormAux.tag}]]*/
null;
var tagName = /*[[${person.contactFormAux.tagName}]]*/
null;
var idPais = /*[[${person.contactFormAux.country}]]*/
null;
var paisName = /*[[${person.contactFormAux.countryName}]]*/
null;
var idProvincia = /*[[${person.contactFormAux.province}]]*/
null;
var provName = /*[[${person.contactFormAux.provinceName}]]*/
null;
var idCity = /*[[${person.contactFormAux.city}]]*/
null;
var cityName = /*[[${person.contactFormAux.cityName}]]*/
null;
var idInst = /*[[${person.contactFormAux.institution}]]*/
null;
var instName = /*[[${person.contactFormAux.institutionNme}]]*/
null;
/*]]>*/
$('#btnAddCForm').trigger('click');
$("#typeField").select2('data', {
id: idType,
text: typeName
});
$("#tagField").select2('data', {
id: idTag,
text: tagName
});
$("#countryField").select2('data', {
id: idPais,
text: paisName
});
$("#provinceField").select2('data', {
id: idProvincia,
text: provName
});
$("#cityField").select2('data', {
id: idCity,
text: cityName
});
$("#institutionField").select2('data', {
id: idInst,
text: instName
});
}
}
P.S. addJury(); and addContactForm(); only closes modal window, both works fine!
EDIT: I'm still waiting for a response...

Function to append modal

I have 3 modals that all have the same format and are activated by different onclicks (Create Contact, Update Contact, Delete Contact). I am wanting the modal-title and modal-body to change depending on which button was clicked. How would I go about creating a function that appends the modal content depending on which button was clicked? Thank you for your help!
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Contact Created!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div>
</div>
I have written the JavaScript "BootstrapModel" class for the same purpose.
It also depends on jQuery so don't forget to embed jQuery before using this class.
class is :
var BootstrapModal = (function (options) {
var defaults = {
modalId: "#confirmModal",
btnClose: "#btnClose",
title: "Confirm",
content: "Some bootstrap content",
onClose: function () {
},
onSave: function () {
}
};
defaults = options || defaults;
var $modalObj = $(defaults.modalId);
var hideModal = function () {
$modalObj.modal("hide");
};
var showModal = function () {
$modalObj.modal("show");
};
var updateModalTitle = function (title) {
defaults.title = title;
//$($modalObj).find(".modal-title").eq(0).html(title);
$modalObj.find(".modal-title").eq(0).html(title);
};
var updateModalBody = function (content) {
defaults.content = content;
$modalObj.find(".modal-body").eq(0).html(content);
};
return {
getDefaults: function () {
return defaults;
},
hide: function () {
hideModal();
},
show: function () {
showModal();
},
updateTitle: function (title) {
updateModalTitle(title);
return this;
},
updateBody: function (body) {
updateModalBody(body);
return this;
}
}
});
Usage :
var emailModal = new BootstrapModal({modalId: "#confirmModal"});
emailModal.updateTitle("Mail sent successfully").updateBody("<br/>This box will automatically close after 3 seconds.").show();
// Hide the Modal
emailModal.hide();
HTML Structure for the Modal:
<div class="modal fade" id="confirmModal" role="dialog" aria-labelledby="thankyouModal" aria-hidden="true" style="overflow-y: hidden;">
<div class="modal-dialog" style="padding-top: 225px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="thankyouModal">Thank you</h4>
</div>
<div class="modal-body">
Thank you. We'll let you know once we are up.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The way I got around this is by loading the data in from external files. So you'd have your initial declaration of your modal box (just the surrounding div), and then in each file you have the containing code for the rest of the modal, then use a bit of jQuery to fire them off:
HTML (in main file)
<div class="modal" id="modal-results" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
JQuery
$('#create-contact').click(function(){
e.preventDefault();
$("#modal-results").html('create-contact.html');
$("#modal-results").modal('show');
});

Submit only first time knockout.js and bootstrap modal

I have problem, with knockout.js and bootstrap modal. On button click i open bootastrap modal, for creating new city. Then i submit form and save in base. Problem is because submiting works only first time. After that it doesn't work.
Here is how it look like
html file
> <!-- Modal add new city
> ==================================================-->
> <div class="modal fade" id="addCity" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
> <div class="modal-dialog">
> <form data-bind="submit: onSubmit">
> <div class="modal-content">
> <div class="modal-header">
> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
> <h4 class="modal-title">Dodaj novi grad</h4>
> </div>
> <div class="modal-body">
> <div class="input-group">
> <span class="input-group-addon">Ime grada</span>
> <input type="text" class="form-control" placeholder="Ime grada" data-bind="value : city_name">
> </div
>
>
> </div>
> <div class="modal-footer">
> <button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
> <button type="submit" class="btn btn-success">Sacuvaj</button>
> </div>
> </div><!-- /.modal-content -->
> </form>
> </div><!-- /.modal-dialog -->
> </div><!-- /.modal -->
js file
var viewModel = ko.computed(function()
{
var self = this;
var cities = getAllCities();
self.cities = ko.observableArray(cities);
self.city_name = ko.observable();
self.logo_path = ko.observable();
//add new city
self.onSubmit = function()
{
var data = JSON.stringify(
{
city_name : self.city_name(), logo_path : self.logo_path()
}); // prepare request data
var response = ajaxJsonPost("/services/private_service/add_city", data, false, false);
if (response.status === ResponseStatus.SUCCESS) {
$("#cityName").attr("value", "");
$('#addCity').modal('hide');
self.cities.push(data);
} else {
//handle error
}
};
});
ko.applyBindings(new viewModel());
Can you not just do an ajax request instead of a form submit? Something like:
$.ajax({
url: "/services/private_service/add_city",
data: data,
success: function (data) {
$("#cityName").attr("value", "");
$('#addCity').modal('hide');
self.cities.push(data);
}
});
Unless you have written script for this method, I'm not familiar with "ajaxJsonPost()".

Categories

Resources