I am new to asp.net MVC 5, I wonder how to use Ajax to call the modal with partial view? i had tried some code but the modal doesn't show up. Any body help?
Here is my code:
View
<script>
#Scripts.Render("~/bundles/jqueryval")
// Create
$(".modalCreate").click(function (e) {
e.preventDefault();
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("Create","Category")',
success: function () {
$(this).attr('data-target', '#createCat');
$(this).attr('data-toggle', 'modal');
// Attach listener to .modal-close-btn's so that when the button is pressed the modal dialog disappears
$('body').on('click', '.modal-close-btn', function () {
$('#createCat').modal('hide');
});
//clear modal cache, so that new content can be loaded
$('#createCat').on('hidden.bs.modal', function () {
$(this).removeData('bs.modal');
});
$('#CancelModal').on('click', function () {
return false;
});
// Init JQuery Validation for view
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
},
error: function (xhr, ajaxOptions, thrownError) {
displayAjaxError(thrownError);
}
});
});
</script>
<p>
#Html.ActionLink("Create Category ", "Create", "Category",
null, new { #class = "modalCreate btn btn-success" })
</p>
<div id="createCat" class="modal fade"
tabindex="-1" role="dialog">
<div class="modal-content">
</div>
</div>
This is my controller:
public ActionResult Create()
{
return PartialView("_Create");
}
// POST: /Category/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CategoryCreateVM productcategory)
{
if (ModelState.IsValid)
{
ProductCategory cat = Mapper.Map<CategoryCreateVM, ProductCategory>(productcategory);
db.ProductCategories.Add(cat);
db.SaveChanges();
TempData["Message"] = "New Category added sucessfully.";
ViewBag.Message = "New Category added sucessfully.";
return RedirectToAction("Index");
}
return PartialView(productcategory);
}
and partial view:
<div class="modal-dialog">
<div class="modal-body">
<div class="modal-content">
#using (Html.BeginForm("Create", "Category", FormMethod.Post))
{
}
</div>
</div>
</div>
I using the boostrap default theme to do. I try to debug in browser inspection it doesnt show any error. But I can sure is it able to find my partial view but the modal never show up. I hope that anyone can help me check my code.
if I understand well this is the way:
1- add your Modal Template in "<script>" part of Views->Shared->_Layout whith specific id for each part of modal to use it every where you want, for example:
<!-- Modal start-->
<div class="modal fade" id="Modalid" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"></button>
<h4 class="modal-title" id="ModalLabelid">Modal title</h4>
</div>
<div class="modal-body" id="ModalBodyid"></div>
</div>
</div>
</div>
<!--Modal End-->
2- then add code below in any view that you want use modal :
<script>
function functionname() {
$("#Modalid").modal();
$("#ModalLabelid").html("YourTitle");
$("#ModalBodyid").load("url of partial view or anything that you want show in modal body");
}
</script>
now if you want load body of modal from some partialview , write the url in .load() method :
$("#ModalBodyid").load("/Controller/Action/");
and if your action should get parameter, add the name of parameter exactly as in action entire :
$("#ModalBodyid").load("/Controller/Action/" + NameOfParameterinAction);
finally to use your script you should call functionname() every where you need from any View :)
Related
How do you get dynamically loaded tabs to work in ASP.Net Core MVC?
I have a simple Index.cshtml that uses bootstrap tabs to create two tabs from the a tags on the page. (To test out options, I first copied from https://qawithexperts.com/article/asp.net/bootstrap-tabs-with-dynamic-content-loading-in-aspnet-mvc/176)
There is a click event on each tab that uses $.ajax() to call the controller and then set the html of the appropriate div.
I have a model with one field, a string that is required.
I have the create view that Visual Studio created.
When I run it and click the first tab, the controller returns PartialView("FirstTabCreate") and loads into the div and everything looks great.
The problem is when clicking the "Create" button.
The controller method checks if IsValid on the ModelState. If not, here is where I run into a problem. If I return the partial view and the model that was passed in I see my validation errors as expected but because I returned the partial view, I lose my tabs. If I return the main view (Index) then the javascript reloads my partial view and has lost the ModelState at that point.
I am not sure what to return so that this works. I have seen lots of examples online that use dynamically loaded tabs but none of them have models or validation.
Code below:
Index Page
#model FirstTab
<!-- Tab Buttons -->
<ul id="tabstrip" class="nav nav-tabs" role="tablist">
<li class="active">
Submission
</li>
<li>
Search
</li>
</ul>
<!-- Tab Content Containers -->
<div class="tab-content">
<div class="tab-pane active" id="FirstTab">
</div>
<div class="tab-pane fade" id="SecondTab">
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$('#tabstrip a').click(function (e) {
e.preventDefault();
var tabID = $(this).attr("href").substr(1);
$(".tab-pane").each(function () {
console.log("clearing " + $(this).attr("id") + " tab");
$(this).empty();
});
$.ajax({
url: "/#ViewContext.RouteData.Values["controller"]/" + tabID,
cache: false,
type: "get",
dataType: "html",
success: function (result) {
$("#" + tabID).html(result);
}
});
$(this).tab('show');
});
$(document).ready(function () {
$('#tabstrip a')[0].click();
});
</script>
FirstTabCreate View
#model WebApplication1.Models.FirstTab
<h4>FirstTab</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="FirstTabCreate">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
Model
using System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
public class FirstTab
{
[Required()]
public string FirstName { get; set; }
}
}
Controller
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public ActionResult FirstTab()
{
return PartialView("FirstTabCreate");
}
public ActionResult FirstTabCreate(FirstTab model)
{
if (!ModelState.IsValid)
{
return View("FirstTabCreate", model);
}
return Content("Success");
}
public ActionResult SecondTab()
{
return PartialView("_SecondTab");
}
}
}
I don't like it but to get it to work, when I click Save, in the Controller method I check if the ModelState is valid. If not, I put the keys and values into a list of custom class and then put that list in the cache. When the child partial view loads it checks to see if there is anything in the cache and if so, parses it back out and uses ModelState.AddModelError().
It's not pretty but it does allow the validation to work.
try to add jquery validation scripts in your code
delete this
<script src="~/lib/jquery/dist/jquery.min.js"></script>
and use this instead
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Add below code to your #section Scripts
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
$.validator.setDefaults({
ignore: []
});
</script>
}
Note: do not add the above inside $(document).ready()
I am trying to show an error message when there is an error when performing a POST form request using Ajax (I don't want the page to refresh). However, the code bellow does not change - it still shows "NO ERRORS" although the TempData["Error] variable is not null (it's set in the controller's action). What I am doing wrong?
That is my _Layout.cshtml (I want to be able to show this error message from every page)
<!DOCTYPE html>
<html>
#*#RenderBody()*#
<head>
</head>
<body>
<div id="divEmp">
#if (TempData["Error"] != null)
{
<div class="alert alert-danger" role="alert">"Error here"</div>
}
else
{
<div class="alert alert-success" role="alert">NO ERRORS</div>
}
</div>
#RenderSection("BodyFill", false)
#RenderBody()
#RenderSection("Scripts", required: false)
</body>
</html>
That is my Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ShareWorkbook(string emails, string title, string id, string queryBuilderId)
{
TempData["Error"] = Res.System_Error_Message;
return NoContent();
}
That is my form (it's located in a partial view and injected at runtime in the main page)
#using DNAAnalysisCore.Resources
#model DNAAnalysisCore.Models.WorkbookShareModel
#* Partial view that contains the 'Share Workbook dialog' modal *#
<!-- Modal -->
<div onclick="activateShareButtons()" class="modal fade" id="shareFormModal" role="dialog">
<div class="modal-dialog modal-md">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Share Workbook - #Model.Title</h4>
</div>
<form id="partialform" asp-action="ShareWorkbook" asp-controller="Home" method="post" data-ajax="true" data-ajax-update="divEmp">
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button onclick="hideDialog()" type="submit" class="btn btn-primary">Share</button>
<button onclick="activateShareButtons()" id="btnCancelDialog" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
You can directly modify the HTML markups using javascript in callback function of Ajax .I assume in your _Layout.cshtml :
<div id="divEmp">
<div id="showError" style="display:none;" class="alert alert-danger" role="alert">"Error here"</div>
<div id="noError" style="display:none;" class="alert alert-success" role="alert">NO ERRORS</div>
</div>
In your page you will use ajax to call server side function , and depend on response you can directly show/modify above area :
$(function () {
$.ajax({
type: "POST",
url: '/Home/GetJobData',
contentType: 'application/json; charset=utf-8',
success: function (response) {
if (response.success) {
$("#showError").hide();
$("#noError").show();
}
else {
$("#showError").show();
$("#noError").hide();
$("#showError").text(response.responseText);
}
},
error: function (response) {
alert("error!");
}
});
})
Server side function :
public IActionResult GetJobData()
{
var isFileSupported = true;
if (!isFileSupported)
{
// Send "false"
return Json(new { success = false, responseText = "Your operation fail !" });
}
else
{
// Send "Success"
return Json(new { success = true, responseText = "Your operation Success !" });
}
}
I'm hoping to use Toastr in ASP.net MVC5 with modal windows. Now, when I click the button on modal window, I'm sending data to one of my controllers via AJAX call and get redirected to the home page. Unfortunately, Toastr notifications are not working in this scenario. In dev console I can see the notification when using break points, though. But with redirect it just doesn't have any time to be seeing on the page. Any suggestions how to make it stay and be visible at the redirect to another page? I'm using Toastr in .done and .fail methods of the AJAX call.
The modal window in the html file:
<div class="modal fade" id="myConfirmModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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>
</div>
<div id="WorkflowConfirmModal" class="modal-body">
Are you sure you want to submit this transaction?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="myID" data-val="#Url.Action("myAction", "myController", null)" data-redirect="#Url.Action("Index", "Home")">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
The AXAJ call in the separate .js file:
$('#myID').on("click", function () {
var reviewData = {
//... my data here
};
$.ajax({
url: $('#myID').data('val'),
type: 'POST',
dataType: 'json',
data: reviewData,
success: function (data) {
if (data.success == true) {
window.location.href = $('#myID').data('redirect');
} else {
$('#myConfirmModal').modal('hide');
bootbox.alert(
"<h4>Submit Errors</h4>" +
"<hr><p>" + data.errors + "</p>");
}
}
})
.done(function () {
toastr.success("Success!");
})
.fail(function () {
toastr.error("Something went wrong.");
});
});
Your browser is off to the races when you issue that window.location command so you have two options:
Route a value ALLLL the way through your controller back into your reloaded view and kick the toastr off there. (This sucks, don't do this)
Restructure your JS so that your window.location call happens after the toastr hide event finishes. something like so :
toastr.error("Content", "Title", {onHidden : function() { alert("do a redirect inside this function");}});
chained Example for first time poster:
var n = $('#n').val();
$('#success').click(function () {toastr.success( $('#g').val(), n, { onHidden : function() { toastr.warning( $('#l').val(), n, { onHidden : function() { toastr.error( $('#r').val(), n, {onHidden : function() { alert( $('#d').val());}, "timeOut": "900"});}, "timeOut": "900"});}, "timeOut": "900"}); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css"><input type="hidden" id="n" value="Never Gonna"><input type="hidden" id="g" value="give you up"><input type="hidden" id="r" value="run around"><input type="hidden" id="l" value="let you down"><input type="hidden" id="d" value="and desert you">
<input type="button" value="Click Me" id="success" />
Example for first option requested by user:
View where BTN is pushed (just append a query string param when you call the controller action - here I am just sending a request to HOME/Index and appending ConfirmS = true as a param):
<div class="btn btn-primary" onclick="location='/?ConfirmS=true'"> GO </div>
Home Controller Index Action method (add a nullable param and if it exists and is true in this case then set a viewbag param to send to our view)
public ActionResult Index(bool? ConfirmS)
{
if (ConfirmS.HasValue && ConfirmS.Value) { ViewBag.ConfirmSubmitMessage = "weeeee"; }
return View();
}
Home Index View (check if your viewbag property exists and if it does then do something like trigger a toastr alert):
#if (ViewBag.ConfirmSubmitMessage != null)
{
<script>alert('#ViewBag.ConfirmSubmitMessage');</script>
}
My final code. The modal window in the html file:
<div class="modal fade" id="myConfirmModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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>
</div>
<div id="WorkflowConfirmModal" class="modal-body">
Your text goes here.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="myID" data-val="#Url.Action("myAction", "myController", null)" data-redirect="#Url.Action("Index", "Home", new { ConfirmToastr = true})">Yes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
The Home Controller/Index Method:
public ViewResult Index(bool? ConfirmToastr)
{
if (ConfirmToastr.HasValue && ConfirmToastr.Value) { ViewBag.ConfirmSubmitMessage = "Foo"; }
return View("Index");
}
The Index.cshtml of Home/Index(). I'm using CDNs here but local taostr.js and taostr.css will do the trick:
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
#if (ViewBag.ConfirmSubmitMessage != null)
{
<script type="text/javascript">
$(function () {
toastr.success("Success.", "Thanks.", {
timeOut: 3000,
onHidden: function () {
window.history.pushState("Name", "Title", "#Url.Action("Index", "Home")");
}
});
});
</script>
}
The AXAJ call in the separate .js file:
$('#myID').on("click", function () {
var reviewData = {
//... your data here
};
$.ajax({
url: $('#myID').data('val'),
type: 'POST',
dataType: 'json',
data: reviewData,
success: function (data) {
if (data.success == true) {
window.location.href = $('#myID').data('redirect');
} else {
$('#myConfirmModal').modal('hide');
bootbox.alert(
"<h4>Submit Errors</h4>" +
"<hr><p>" + data.errors + "</p>");
}
}
})
});
I'm trying to learn more about MVC 5 so I'm writing a bloging site for myself to learn more as I go.
I have set up a select list for tags and would like to be able to add new tags from the create blog entry page rather than having to remember to set the tags up before creating a new post. I'm thinking down the lines of a "Add Tag" button which displays a bootstrap modal window where the user can add a new tag.
Here is my controller action:
public ViewResult CreateBlogPost()
{
CreateEditBlogViewModel viewModel = new CreateEditBlogViewModel();
viewModel.BlogPost = new Core.BlogPost();
viewModel.BlogPost.ShortBody = "<p>Something short and sweet to describe the post</p>";
viewModel.BlogPost.Body = "<p>Enter something blog worthy here...</p>";
viewModel.Tags = new SelectList(_blogRepo.BlogTags(), "Id", "Name");
viewModel.Categories = new SelectList(_blogRepo.BlogCategories(), "Id", "Name");
return View(viewModel);
}
And here is the HTML in the view:
<div class="row">
<div class="form-group">
#Html.LabelFor(m => m.BlogPost.Tags, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.ListBoxFor(m => m.SelectedTags, Model.Tags, new { #class = "form-control chosen-select", #data_placeholder = "Start typing to see a list of tags" })
</div>
</div>
</div>
<div class="row">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#tagModal">
Add Tag
</button>
</div>
Here is my partial view for the modal window:
#using (Html.BeginForm("SaveTag", "Home", FormMethod.Post, new { id = "tag-form" }))
{
#Html.AntiForgeryToken()
<!-- Modal -->
<div class="modal fade" id="tagModal" tabindex="-1" role="dialog" aria-labelledby="tagModalLabel">
<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="tagModalLabel">Enter a name for a new tag</h4>
</div>
<div class="modal-body">
<input type="text" id="Name" placeholder="Enter a new tag name" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
}
Is it possible to add a tag on the client side, persist it into the db and then add it to my tags select list without refreshing the page?
PS: FYI I'm using the Chosen multi-select from here.
#section scripts {
<script type="text/javascript" src="~/Scripts/chosen.jquery.min.js"></script>
<script type="text/javascript">
$(".chosen-select").chosen()
</script>
}
EDIT: I have updated the question with all the code that makes the view give the user the modal window to enter a new tag name. I'm just not sure how to post without navigating away from the page so I'm guessing some sort of Ajax post is required. And then what to do with the data that is returned from that post. How do I then add that new persisted record to the select list?
I know the tag isn't passing to the controller method as it's not bound to any sort of model but being as I'm using a view model on the parent view, I'm not sure how I would handle that here either.
In order to dynamically add a new BlogTag in the view you will need to post the new tag Name using ajax, to a controller method that saves the BlogTag and returns its new ID value. Your controller method would be something like
[HttpPost]
public JsonResult CreateTag(string name)
{
BlogTag tag = new BlogTag(){ Name = name };
db.BlogTags.Add(tag);
db.SaveChanges();
return Json(tag.ID);
// If the above code could result in an error/exception, catch it and return
// return Json(null);
}
Then in the view, handle the dialogs submit button to post the value and update the tag list
var url = '#Url.Action("CreateTag")';
var tagList = $('#SelectedTags');
$('#tag-form').submit(function() {
var tagName = $('#Name').val();
$.post(url, { name: tagName }, function(id) {
if (id) {
// add the new tag to the list box
tagList.append($('<option></option>').val(id).text($('#Name').val()));
// trigger the chosen update
tagList.trigger("chosen:updated");
} else {
// Oops - display an error message?
}
}).fail(function (result) {
// Oops - display an error message?
});
return false; // cancel the default submit
});
Side note: I would recommend that you create a view model for BlogTagVM (containing a property for the Name with validation attributes) and an associated partial view (say _AddBlogTag.cshtml) that generates the dialog html, so that in the main view you can use #Html.Partial("_AddBlogTag", new BlogTagVM()) which will allow you to use the strongly typed html helpers, and to include client side validation.
Note also that nested <form> elements are invalid html so ensure that html for the dialog is outside the main <form> tag for the view.
I am doing something similar, I think it might help. In my case, I'm "moving" values from one list to another (from "available" to "used") and then saving the values of the "used" list. Anyway, in the controller, the "used" list shows up as an array of strings. Here's my code:
public ActionResult PinchHit(FormCollection form, LineupViewModel lvm, String[] UsedPlayers)
{
[Snip]
if (ModelState.IsValid && lineupResults.IsValid)
{
[Snip]
foreach (String usedID in UsedPlayers)
{
gameState.HomeUsedPlayersIDs.Add(Convert.ToInt32(usedID));
}
uow.Repository<GameState>().Update(gameState);
uow.SaveChanges();
return RedirectToAction("Index", "GameSummary");
}
[Snip]
return View(lvm2);
}
Hope that helps.
Per my comment:
Here is an AJAX call-back mechanism I used to retrieve data from the database without reloading the page, you could use it to save data to the database instead.
<script type="text/javascript">
function getPositions(id, control) {
$.ajax({
url: "#Url.Action("GetPositions", "Lineup")",
data:
{
id: id
},
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
$(control).html("");
$.each(data, function (i, item) {
$(control).append("<option value=\"" + item.Value + "\">" + item.Text + "</option>");
}
);
}
});
}
</script>
then in the controller:
[HttpPost]
public ActionResult GetPositions(int id)
{
Player player = uow.Repository<Player>().GetById(id);
if (player == null)
{
return (null);
}
List<SelectListItem> positionList = new SelectList(player.Positions, "ID", "ShortName").ToList();
return Json(positionList);
}
Pretty standard stuff really.
As mentioned in the title, the modal does not show up.
The content of the form is loaded via formly and the content of the template seems to load, but it only shows the modal very thin, with the overlay but not the content.
I have a main controller in which I have:
$scope.add = function(){
$modal.open({
templateUrl: 'app/js/templates/popupAddCarForm.html',
controller: 'FormsController',
controllerAs: 'vm',
backdrop: 'static',
resolve: {
formData: function(){
return {
fields: getFormFields(),
model: {}
}
}
}
});
};
My html is like so:
<script type="text/ng-template" id="popupAddCarForm">
<div class="modal">
<div class="modal-dialog">
<div class="modal-header">
<h3 class="modal-title">Adauga masina</h3>
</div>
<div class="modal-body">
<form name="vm.addCarForm">
<formly-form model="vm.formData.model" fields="vm.formData.fields">
</formly-form>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="submit" >Adauga</button>
</div>
</div>
</div>
And my form controller like so:
davidintercar.controller('FormsController',
function($modalInstance, formData) {
var vm = this;
//debugger;
vm.formData = formData;
vm.originalFields = angular.copy(vm.formData.fields);
}
);
The result is like so:
LATER EDIT:
In order to rid ourselfes of other doubts, here is the code from the demo:
app.controller('ModalInstanceCtrl', function ($modalInstance, formData) {
var vm = this;
debugger;
// function assignment
vm.ok = ok;
vm.cancel = cancel;
// variable assignment
vm.formData = formData;
vm.originalFields = angular.copy(vm.formData.fields);
// function definition
function ok() {
$modalInstance.close(vm.formData.model);
}
function cancel() {
$modalInstance.dismiss('cancel');
};
});
Link: angular-formly.com/#/example/integrations/ui-bootstrap-modal
LATER, LATER EDIT:
Plunker: http://plnkr.co/edit/8wgL4t2oXsFFeLBKGGW8?p=preview
Folder Structure:
--app
----js
------controller
------services
------templates
------view
----app.js
intex.html
My popupAddCarForm.html is in the templates directory, but as you see in the plunker, it does not render my loaded content, even in the same directory although a separate template file.
The modal template don't need to have the modal and modal-dialog layer - they will be generated by bootstrap.
<script type="text/ng-template" id="popupAddCarForm.html">
<div class="modal-header">test
<h3 class="modal-title">Adauga masina</h3>
</div>
<div class="modal-body">
<form name="vm.addCarForm">
<formly-form model="vm.formData.model" fields="vm.formData.fields">
</formly-form>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="submit" >Adauga</button>
</div>
</script>