How to reload angularJs ng-table - javascript

I have an ng-table. I have multiple ng-tables inside one controller. I am giving dynamic attributes i.e. ng-table="tableParams2" or ng-table="tableParams3" etc. to them.
I am making an ajax request on button click function to update the data. My http request is being sent at backend. By after I click 3-4 times, I see in console my table is reloaded. By after data, my data remains constant, I don't see the reloaded content in table. Below is my code:
Html:
<button ng-click="qualifyX(2)" ></button>
<div class="dragable modal hide fade ui-draggable in" id="ptn_popup" aria-hidden="false" data-backdrop="false">
<div class="modal-header">
<a class="close" data-dismiss="modal" data-original-title="" title="">×</a>
<h4>Possible matched Companies</h4>
</div>
<div class="modal-body" style="padding: 10px;">
<div id="ptn_qualify_res" class="grid-view">
<div class="summary"></div>
<table ng-table="tableParams2" show-filter="true" class="items table table-striped table-bordered table-condensed">
<tr ng-repeat="business in $data">
<td data-title="'Primary Trading Name'" sortable="'primary_trading_name'" filter="{ 'primary_trading_name': 'text' }">
{{business.primary_trading_name}}
</td>
<td data-title="'Primary Entity Name'" sortable="'primary_entity_name'" filter="{ 'primary_entity_name': 'text' }">
{{business.primary_entity_name}}
</td>
<td data-title="'Business Name(s)'" sortable="'business_names'" filter="{ 'business_names': 'text' }">
{{business.business_names}}
</td>
<td data-title="'Other Trading Name(s)'" sortable="'other_trading_names'" filter="{ 'other_trading_names': 'text' }">
{{business.other_trading_names}}
</td>
<td data-title="'State'" sortable="'state'" filter="{ 'state': 'text' }">
{{business.state}}
</td>
<td style="width:70px;">
<a data-dismiss="modal" href="javascript:void(0)" data={{business.business_id}} class="ptn_qualify_view_link">
<button type="button" class="btn btn-mini"><i class="icon-eye-open"></i> View </button>
</a>
</td>
</tr>
</table>
</div>
</div>
<div class="modal-footer">
<a data-dismiss="modal" class="btn" id="yw11" href="javascript:void(0);" data-original-title="" title="">Close</a>
</div>
</div>
App.js
$scope.qualifyX = function(busID) {
var penModal = $('#popups_container' + busID + ' #pen_popup');
var pen = $('#popups_container' + busID).next().find('input#Custombusiness_primary_entity_name').val();
var selectors = {pen: pen, penModal: penModal};
$http.get(getPtnData + '?ptn=' + selectors.ptn).success(function(data) {
selectors.ptnModal.find('#ptn_qualify_res').removeClass('grid-view-loading').addClass('grid-view');
$scope['tableParams' + busID] = new ngTableParams(
{
page: 1, // show first page
count: data.length, // count per page
sorting:
{
primary_trading_name: 'asc' // initial sorting
}
}, {
total: 0, // length of data
getData: function($defer, params) {
var filteredData = params.filter() ?
$filter('filter')(data, params.filter()) :
data;
var orderedData = params.sorting() ?
$filter('orderBy')(filteredData, params.orderBy()) :
data;
params.total(orderedData.length); // set total for recalc pagination
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
});
};
Create a somewhat similar Plunker, on every click I want to reload the table with new data.

I was having a very similar problem where my table was rendering but not reloading upon an action. What you need to do is to reload $scope.tableParams every time your button is clicked. A simple way to do this is to wrap $scope.tableParams.reload() in a function, and then call that function when the button is clicked.
controller code:
$scope.doSearch = function () {
$scope.tableParams.reload();
}
html code:
<button ng-click="doSearch()">Search</button>

I resolved finally the problem.
When I received the update data for the table it's necessary reload the table as follows:
$scope.tableData = data;
$scope.tableParams.total($scope.tableData.length);
$scope.tableParams.reload();

in case anyone else hits this. I created my own filter that creates a new size array.
I used
$scope.tableParams.total(data.length)
to update the length before reloading the table.

This code works for me ,
write it in your function- where you get your dynamic data
$scope.tableParams.reload();
$scope.tableParams.page(1);
$scope.tableParams.sorting({});

Related

Display Data on Dialogbox without reloading page

am trying to display bootstrap dialog box with ID + Name + Price on it.
Then if user choose YES on the dialog, it must hit the Action method where there’s delete function and refresh the data on the page to see the change without reloading the page.
Also I don’t want after it hits the Delete user action method, it must not display its View.
I tried to use ViewBag from the below code but it doesn’t show me the ID + Name + Price on the Bootstrap Dialogbox, and doesn’t redirect to delete action method, and doesn’t refresh the page
#model IEnumerable<School.Models.ApplicationUser>
<hr>
<table class="table table-responsive table-hover">
<tbody>
#foreach (var item in Model.OrderBy(x => x.DateTime))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<span style="color: #ff0000;">
<a class="btn btn-warning btn-sm disclaimer-dialog">
<i class="fa fa-unlock"> </i>Delete
ViewBag.MyId = #item.Id;
</a>
</span>
</td>
#ViewBag.MyId
</tr>
}
</tbody>
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/Views/SchoolAccounts/Delete.js")
}
<!-- Button trigger modal -->
<!-- Modal -->
<div class="modal fade" id="disclaimerModalDialog" tabindex="-1" role="dialog" aria-labelledby="exampleModalScrollableTitle" aria-hidden="true" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalScrollableTitle">Confirmation Deletion</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p><strong>Are you sure you want to reset password for user ? #ViewBag.MyId </strong></p>
#using (Html.BeginForm("DeleteProduct", "SchoolAccounts",
FormMethod.Post, new
{
#id = "delete-form",
role = "form"
}))
{
#*#Html.HiddenFor(m => m.Id)
#Html.AntiForgeryToken()*#
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
onclick="$('#delete-form').submit();">
Yes
</button>
<button type="button" class="btn btn-primary"
data-dismiss="modal">
No
</button>
</div>
</div>
</div>
</div>
Content of Delete.js
$(function () {
$('.disclaimer-dialog').click(function () {
$('#disclaimerModalDialog').modal('show');
});
});
ViewBag can't be used like that. Once ViewBag is rendered on a page, you can't update its value. All razor variables are static once the page has finished loading.
What we need to do is assign those values on the html attributes.
Modify the link in your loop to have data-properties. I used data-id, data-name, data-price;
#foreach (var item in Model.OrderBy(x => x.DateTime))
{
<tr>
#*just modify the link in the last column*#
<td>
<span style="color: #ff0000;">
<a data-id="#item.Id" data-name="#item.Name" data-price="#item.Price" class="btn btn-warning btn-sm disclaimer-dialog">
<i class="fa fa-unlock"> </i>
Delete
</a>
</span>
</td>
</tr>
}
Modify your Delete.js to access those attributes and replace the content of the modal.
$(function () {
$('.disclaimer-dialog').click(function () {
// get attributes from the button
var id = $(this).data("id");
var name = $(this).data("name");
var price = $(this).data("price");
// Assign value to delete-id
$(".delete-id").val(id);
// update the first paragraph in modal-body
$('#disclaimerModalDialog').find(".modal-body p").eq(0).html("Are you sure you want to delete "+id+"-"+name+"-"+price+"?");
$('#disclaimerModalDialog').modal('show');
});
});
In your modal body, use this for the input field. We need to add a class so we can easily access it;
#Html.HiddenFor(m => m.Id, new { #class="delete-id" });
Add this function to your Delete.js
$(function(){
$("#delete-form").submit(function(e){
// this will stop the page from refreshing or redirecting
e.PreventDefault();
var deleteId = $(".delete-id").val();
var passData = { id:deleteId };
// ajax call here
$.ajax({
type: "POST",
url: "/ControllerName/DeleteAjax",
data: JSON.stringify(passData),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function(result){
alert(result);
// find the link with data-id == deleteid
// .parent() = span
// .parent().parent() = td
// .parent().parent().parent() = tr
// .remove() = remove that row
$("table a[data-id='"+deleteId+"']").parent().parent().parent().remove();
},
error: function(err){
alert(err);
}
});
});
});
In your controller, add this function. DeleteAjax;
[HttpPost]
public ActionResult DeleteAjax(string id)
{
var product = context.Products.FirstOrDefault(p=>p.Id == id);
if(product == null){
return Content("error, cant find Id")
}else{
context.Products.Remove(product);
context.SaveChanges();
return Content("successfully deleted");
}
}

Modal doesn't come with input's values

I have to use modals in my project. But unfortunately it does not work well.
On the page, when I click on the Add New Role button, everything goes right. But then when I click on the role edit button, the modal is displayed with blank values. While the IDs are successfully sent to the action.
After that when you reload the page, and first click on the edit role button, the modal will not display at all. At the same time, if you click the Add New Role button again, the modal is successfully displayed and everything is OK. At the same time, if you click the role edit button again, the modal will be displayed again in blank. (Just as before the IDs were successfully sent to the action but not found). I think this problem is related to two things:
The problem is with the action (maybe the code I wrote didn't send
the values well)
The problem may be that the following JQuery codes is not
performing well:
Jquery (file name: application-role-index.js):
(function ($) {
function RoleList() {
var $this = this;
function initilizeModel() {
$("#modal-action-application-role").on('loaded.bs.modal', function (e) {
}).on('hidden.bs.modal', function (e) {
$(this).removeData('bs.modal');
});
}
$this.init = function () {
initilizeModel();
}
}
$(function () {
var self = new RoleList();
self.init();
})
}(jQuery))
Anyway i hope you can help me. Here is the code I will use for this section:
Action in 'RoleListController':
[HttpGet]
public async Task<IActionResult> AddEditRole(string Id)
{
RoleListViewModel model = new RoleListViewModel();
if (!string.IsNullOrEmpty(Id))
{
ApplicationRole applicationRole = await _roleManager.FindByIdAsync(Id);
if (applicationRole != null)
{
model.Id = applicationRole.Id;
model.Name = applicationRole.Name;
model.Explanation = applicationRole.Explanation;
}
return PartialView("_AddAndEditAppRole", model);
}
else
{
return PartialView("_AddAndEditAppRole");
}
}
The View page i'm using modal:
<div class="btn-group">
<a class="btn btn-primary" id="showaddrole" data-toggle="modal" asp-action="AddEditRole" data-target="#modal-action-application-role">افزودن نقش جدید</a>
</div>
<table dir="rtl" class="table table-bordered table-striped myTable table-condensed">
<thead>
<tr>
<th>ID</th>
<th>#Html.DisplayNameFor(Model => Model.Name)</th>
<th>#Html.DisplayNameFor(Model => Model.Explanation)</th>
<th>#Html.DisplayNameFor(Model => Model.NumberOfUsers)</th>
<th>عملیات</th>
</tr>
</thead>
<tbody>
#foreach (var role in Model)
{
<tr>
<td>#role.Id</td>
<td>#role.Name</td>
<td>#role.Explanation</td>
<td>#role.NumberOfUsers</td>
<td>
<a class="btn btn-info myTableIC" asp-route-id="#role.Id" asp-action="AddEditRole" data-target="#modal-action-application-role" data-toggle="modal">
<i class="glyphicon glyphicon-pencil"></i>
</a>
<a class="btn btn-danger myTableIC" asp-route-id="#role.Id" asp-action="DeleteRole">
<i class="glyphicon glyphicon glyphicon-remove"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
#Html.Partial("_Modal", new BootstrapModel { ID = "modal-action-application-role", Size = ModalSize.Medium })
#section Scripts{
<script src="~/js/modal-js/application-role-index.js"></script>
}
I have prepared a short video of how my program works so you can move forward with a better understanding:
You can find that by this link...
i suggest a solution at first create a div block with a unique id
<div id="popup"></div>
than use ajax to call the action like this :
$("#btnAdd").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("AddEditRole")',
success: function (result) {
$("#popup").html(result);
$("#popup-addRole").modal("show");
}
});
});
then create an partiel view of popup with the id of model is popup-addRole something like this
<div class="modal" id="popup-edt" role="dialog">
<div class="modal-dialog" role="document" style="width:50%;">
<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>
</div>
<div class="modal-body">
//add your form here
</div>
</div>
</div>
</div>
don't forget to add model you want to use
i hope that fix the problem

unwanted angular value link

The picture shows an edit page, which use can add commands to the list, delete and so on. The value should be only updated to the actual array when user click update button. Below are some of my code:
$scope.editSchedule = function(index){
console.log(index);
$scope.editScheduleValue = {
name: $scope.currentSchedule[index].name,
trigger: $scope.currentSchedule[index].trigger,
repeat: $scope.currentSchedule[index].repeat,
commandList: $scope.currentSchedule[index].commandList,
scheduleIndex: index
};
var dailog = $uibModal.open({
templateUrl: 'app/partials/edit-schedule.html',
controller: editScheduleController,
size: 'lg',
scope: $scope
});
};
This is a edit button scope, which will get the actual value from curremtSchedule array.
$scope.addCommand = function(){
console.log("addCommand");
$scope.addRoom = $scope.equipment[$scope.roomSelected].name;
$scope.addEquipment = $scope.equipment[$scope.roomSelected].equipment[$scope.equipmentSelected].name;
$scope.addEquipmentCommand = $scope.equipment[$scope.roomSelected].equipment[$scope.equipmentSelected].command[$scope.commandSelected].type;
$scope.editScheduleValue.commandList.push({
room: $scope.addRoom,
equipment: $scope.addEquipment,
command: $scope.addEquipmentCommand
})
};
This is my Add command button code, which push data to editScheduleValue array.
HTML:
<tr ng-repeat="x in editScheduleValue.commandList" ui-tree-node>
<td style="width: 5%"><i class="glyphicon glyphicon-resize-vertical" ui-tree-handle></i> </td>
<td style="width: 5%">{{$index+1}}</td>
<td style="width: 30%">{{x.room}}</td>
<td style="width: 30%">{{x.equipment}}</td>
<td style="width: 30%">{{x.command}}</td>
<td>
<a class="pull-right btn btn-danger btn-xs" data-nodrag ng-click="remove(this)">
<span class="glyphicon glyphicon-remove"></span>
</a>
</td>
</tr>
The problem that I encouter is whenever I delete, add command not only the editScheduleValue array updated, but the currentSchedule array as well, I really do not understand why is this 2 array is somehow linked. Please help~~~
Thank you.
I replace
commandList: $scope.currentSchedule[index].commandList,
With
commandList: angular.copy($scope.currentSchedule[index].commandList),
and this 2 arrays are not link anymore, I do not quite understand why it is, but here the answer for my problem.

AngularJS dynamic routing from index to detailed page

I'm trying to route from an index list of items to a page that will display a detailed view of that item.
In my index view I have a table that iterates through all the items that are saved in the database.
There is a button under the actions column that will take me to events/show route using ng-click="go('events/show')"
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Title</th>
<th class="col-md-2">Actions</th>
</tr>
</thead>
<tbody>
<tr scope="row" ng-repeat="event in events | reverse | filter:filterByUID">
<td>{{event.title}}</td>
<td class="col-md-2">
<div class="btn-group" role="group" aria-label="actions">
<button class="btn btn-primary" ng-click="go('events/show')">
<span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>
</button>
<button class="btn btn-primary" ng-click="events.$remove(event)">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</div>
</td>
</tr>
</tbody>
</table>
The table looks like this:
In my controller I have:
$scope.go = function ( path ) {
$location.path( path );
};
in my routes.js I have:
.whenAuthenticated('/events/show', {
templateUrl: 'views/eventShow.html',
controller: 'eventShowCtrl'
})
Everything works so far.
However, what is unclear to me is how do I pass the event id to the eventShow.html page, so I know which item was clicked from the index list, so I can display the detailed information?
My firebase database looks like this:
Check out ui-router, it makes dynamic routing much easier
https://github.com/angular-ui/ui-router
But if you want to keep what you have, you should pass the event id into your path, like such
$scope.go = function ( path, event ) {
$location.path( path + "/" + event.id );
};
.whenAuthenticated('/events/show/:eventId', {
templateUrl: 'views/eventShow.html',
controller: 'eventShowCtrl'
})
and in your controller, access $stateParams.eventId to load that event.
You should use a variable in your router:
.whenAuthenticated('/events/:id', {
templateUrl: 'views/eventShow.html',
controller: 'eventShowCtrl'
})
Then you can simply use the ID in your function call:
go('events/:id')
Here's a great tutorial (and I highly recommend watching all of both parts).
And you'll have nicer URLs that can be bookmarked.
One you could pass the UID(uid is just an example for user id) onClick
<tr scope="row" ng-repeat="event in events | reverse | filter:filterByUID">
<td>{{event.title}}</td>
<td class="col-md-2">
<div class="btn-group" role="group" aria-label="actions">
<button class="btn btn-primary" ng-click="go('events/show', event.UID)">
<span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>
</button>
<button class="btn btn-primary" ng-click="events.$remove(event)">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</div>
</td>
</tr>
Then in your js file
$scope.go = function ( path, uid ) {
$location.path( path + "/" + uid );
};
.whenAuthenticated('/events/show/:eventId', {
templateUrl: 'views/eventShow.html',
controller: 'eventShowCtrl'
})
Then to query firebase, say you have a field in your objects called uid, you can use startAT and endAT methods.
See here for example
And here to read more on filtering

Populate angular ui bootstrap popover

How do you populate an angular ui bootstrap popover? I want to populate the popover with a list of actor names. Here is the code:
<div class="container" ng-if="radioModel=='Search for Actor'">
<p>Movies played in:</p>
<table class="table table-bordered">
<tr ng-repeat="name in listOfMovies">
<td>
<p>
<button uib-popover="populateWithListOfData" popover-trigger="mouseenter" type="button" class="btn btn-default"> {{ name }}</button>
</p>
</td>
</tr>
</table>
</div>
I want to be able to populate this popover for each name of the ng-repeat. So I will get a name of a movie and based on that name I want to populate the popover with a list of actors in that movie. Thanks guys.
This is definitely possible.
I have setup a data item called friends in JS
$scope.friends = [
{name:'John'},
{name:'Jessie'},
{name:'Johanna'},
{name:'Joy'}
];
Also , an array was created for the text in the popup
$scope.toolTip =['D','A','C','T'];
If you want to display a pop up for each row.
I've created the ng-repeat and the relevant popover.In order to display all the letters in the first popover.
<div ng-repeat="f in friends">
{{f.name}}
<button uib-tooltip="{{toolTip[$index]}}" type="button" class="btn btn-default">Tooltip {{placement.selected}}</button>
</div>
Here is a working demo
How does it works?
Your tool tip value is set as uib-tooltip="{{toolTip[$index]}}".it accesses each element according to the $index obtained from ng-repeat.
If you want to display all the data in the first pop up
I've created the ng-repeat and the relevant popover.In order to display all the letters in the first popover.
<div ng-repeat="f in friends">
<div ng-if="$index==0">
<button uib-tooltip="{{toolTip}}" type="button" class="btn btn-default">Tooltip {{placement.selected}}</button>
</div>
{{f.name}}
</div>
Here is a working demo
How does it works?
Your tool tip value is set as uib-tooltip="{{toolTip}}".It enters the ng-if , if the condition is met, and thus prints the array.
I couldn't test if it works, but this might give you the idea.
(function ()
{
function moviePopover($compile)
{
return {
restrict: "EA",
scope: true,
templateUrl: '<button uib-popover-template="dynamicPopover.templateUrl" popover-title="{{dynamicPopover.title}}" type="button" class="btn btn-default">Popover With Template</button>',
link: function (scope, element, attrs)
{
scope.dynamicPopover = {
content: "Movies",
templateUrl: "myPopoverTemplate.html",
title: "Title"
};
if (attrs.movieName !== undefined)
{
scope.movieList = getMoviesByName(attrs.movieName);
$compile(element)(scope);
//If 1st leads to infinit loop use this
// $compile(element.contents())(scope);
}
function getMoviesByName(movieName)
{
//return all moviews based on movieName
//here im just returning dummy array(you return your data)
return ["Movie1", "Movie2"];
}
}
}
}
angular.module("myApp").directive("moviePopover", ["$compile", moviePopover]);
}());
<script type="text/ng-template" id="myPopoverTemplate.html">
<ul>
<li ng-repeat="movie in movieList">{{movie}}</li>
</ul>
</script>
<div class="container" ng-if="radioModel=='Search for Actor'">
<p>Movies played in:</p>
<table class="table table-bordered">
<tr ng-repeat="name in listOfMovies">
<td>
<p>
<movie-popover movie-name="{{name}}"></movie-popover>
</p>
</td>
</tr>
</table>
</div>

Categories

Resources