How to refresh ng-repeat table in AngularJS onclick button? - javascript

I can not update the value of the fields in the table with ng-repeat in any way onclick of a JS function, not even with a $ scope.apply () or with a timeout.
This is my HTML Code :
<div class="container">
<table class="table" id="table">
<thead class="table-bordered">
<th ng-repeat="(column_name,v) in response[0];">{{column_name}}<br>
<b>Class:</b>
<a ng-click="chooseClass(column_name)" id="{{column_name + 1}}">
{{kls_dict[column_name][0]}}
</a>
<br>
<b>Transfs:</b>
<a ng-click="chooseTrf(column_name)" id="{{column_name + 2}}">
{{kls_transfs[kls_dict[column_name][0]][0]}}
</a>
</th>
</thead>
<tbody>
<tr ng-repeat="row in response">
<td ng-repeat="value in row">{{value}}</td>
</tr>
</tbody>
</table>
</div>
And this is my JS function called in another HTML button component :
$scope.save_params = function (old_transformation, object) {
console.log("Enter save_params");
console.log("trfs", old_transformation)
console.log(object)
console.log('class', $rootScope.old_class)
console.log('columns_name', $rootScope.show_column_name)
to_send = {
'class': $rootScope.old_class,
'column_name': $rootScope.show_column_name,
"trfs": old_transformation,
"params": object
}
$rootScope.spm.close();
$http({
url: "/send_parameters",
method: "POST",
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(to_send)
}).success(function (data) {
console.log(data)
}).error(function () {
console.error('Errore durante invio dei parametri');
$("#warning-alert").text("Errore durante l'invio dei parametri, riprovare o controllare i parametri specificati");
$("#warning-alert").fadeTo(2000, 500).slideUp(500, function () {
$("#warning-alert").slideUp(500);
});
});
};
I have already specify the AngularJS controller. Thanks everyone :)

Related

How do i tell ajax to select the item clicked from a list

Im trying to make a list of people in vacations and I want to calculate their date of return when i click the "Data de Regresso" link. I managed to do that but when I click any of the buttons in the list it always passes the first ID in the list and not the ID of the item I clicked. I'm kinda new to this. I would really aprecciate any help.
Im using asp.net framework MVC 5.
Here is the View Code:
<div class="col-4">
<div class="card">
<div class="card-header text-white" style="background-color: #4d4d4f;">
Férias
</div>
<div class="card-body">
<table class="table">
<thead>
<tr>
<td>Nome</td>
<td></td>
</tr>
</thead>
<tbody>
#if (Model.PessoasDFVM.Count == 0)
{
<tr>
Ninguém de férias.
</tr>
}
else
{
foreach (PortalInternoBBG.Web.Models.HomePage.PessoaDFVM pessoaDeFerias in Model.PessoasDFVM)
{
<tr>
<td>#pessoaDeFerias.Nome</td>
<td>
<div id="ResponseDiv">
<a href="#" onclick="GetDataDeRetorno('#pessoaDeFerias.IDstring')">
Data de Regresso
</a>
</div>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
And the ajax function:
function GetDataDeRetorno(id) {
var stringID = id;
$.ajax({
url: urlCalculaDataDeRetorno,
data: { "id": stringID },
type: "POST",
success: function (data) {
$('#ResponseDiv').replaceWith("<div>" + data + "</div>");
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
Append div class with the unique Id so that you will change the div data in ajax response with the help of it.
Please change the below code in html.
<div class="ResponseDiv_#pessoaDeFerias.IDstring">
<a href="#" onclick="GetDataDeRetorno('#pessoaDeFerias.IDstring')">
Data de Regresso
</a>
</div>
and in ajax success with the below code
success: function (data) {
$('.ResponseDiv_' +stringID).replaceWith("<div>" + data + "</div>");
}

Adding delete button to bootstrapTable in MVC

I have a .Net MVC project that fills a table with data using a bootstrapTable from bootstrap v3. I want to add a delete button to each row.
The bootstrapTable takes json data and loads it. The json is built like this:
public virtual JsonResult Search(FormCollection searchArgument)
{
IEnumerable<MyData> myListData = GetMyListData(searchArgument);
var jsonResult = Json(myListData, JsonRequestBehavior.AllowGet);
return jsonResult;
}
So the jsonResult is just a list of all of my MyData. My view that shows the result looks like this:
#model MyNamespace.Web.Models.MyListViewModel
<div class="col-md-12">
#{
ViewBag.Title = "Index";
Layout = MVC.Shared.Views._Layout;
<div class="row">
<div class="col-md-12">
<form role="form" id="formsearch">
<input id="fromsearch" name="fromsearch" type="hidden" value="true" />
<div class="form-group">
#Html.LabelFor(m => m.Status, "Status:")<br />
#Html.DropDownList("status", new SelectList(Model.Status, "Value", "Key", Model.SelectedStatus), new { #class = "selectButton" })
</div>
<input type="button" id="btnsearch" value="Search" />
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
</tr>
</thead>
</table>
</div>
</div>
}
</div>
<script>
$("#btnsearch").click(function () {
$('#table').bootstrapTable('showLoading');
$.ajax({
type: "POST",
url: "#Url.Action(MVC.MyController.ActionNames.Search, MVC.MyController.Name)",
data: $('#formsearch').serialize(),
dataType: "json",
success: function (data) {
$('#table').bootstrapTable('hideLoading');
$('#table').bootstrapTable({
data: data,
striped: true,
pagination: true,
pageSize: 25,
pageList: [10, 25, 50, 100, 200],
search: false
});
$('#table').bootstrapTable('load', data).on('click-row.bs.table', function (e, row, $element) {
Showdetail(JSON.stringify(row));
});
},
error: function (err) {
console.log(err)
}
});
});
function Showdetail(jsonrow) {
var obj = JSON.parse(jsonrow);
window.location = "#Url.Action(MVC.MyController.ActionNames.ShowMyData, MVC.MyData.Name)?myDataId=" + obj.Id;
}
</script>
#section AddToHead
{
#Styles.Render("~/bundles/bootstrap-table/css")
}
#section scripts
{
#Scripts.Render("~/bundles/bootstrap-table")
}
So the javascript function ("#btnsearch").click gets the json data from public virtual JsonResult Search and sends that to bootstrapTable which loads the data in the table. What I want to do is to add a new header in my table, like this:
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
<th></th>
</tr>
</thead>
</table>
And then in the last column add a delete button that has the id of that row (#Model.Id for instance) so that I can call the controller to delete the row from the database and then reload the table so that the row also disappears from the GUI.
I could easily do it with an ActionLink but since I don't loop through all objects and then draw them out on the page, I can't just add an ActionLink to the page. All the rendering of the rows is done in the bootstrapTable.
I looked at this question and answer and it seemed promising but it's not quite what I'm doing and I can't get my head around what I would need to do to get it working for me: Bootstrap table - dynamic button in row.
According to documantation and examples here:
https://live.bootstrap-table.com/example/column-options/events.html
Add to your scripts:
<script>
var $table = $('#table')
function operateFormatter(value, row, index) {
return [
'<a class="remove" href="javascript:void(0)" title="Remove">',
'<i class="fa fa-trash"></i> Delete',
'</a>'
].join('')
}
window.operateEvents = {
'click .remove': function (e, value, row, index) {
//edit here for ajax request to delete row.id record
$.ajax({
type: "POST",
url: "#Url.Action(MVC.MyController.ActionNames.Delete,MVC.MyController.Name)",
data: {id:row.id},
dataType: "json",
success: function (data) {
//when success remove row
$table.bootstrapTable('remove', {
field: 'id',
values: [row.id]
})
},
error: function (err) {
console.log(err)
}
});
}
}
</script>
and edit your html table:
<table id="table" class="table">
<thead>
<tr>
<th data-field="MyDataNumber" data-sortable="true">Number</th>
<th data-field="MyDataCreatedate" data-sortable="true">Created</th>
<th data-field="Status" data-sortable="true">Status</th>
<th data-field="operate" data-formatter="operateFormatter" data-events="operateEvents">Actions</th> <!--add this col-->
</tr>
</thead>
</table>

Adding to List<Model> using JQuery

I have a ViewModel with a parameter List. In the View, the user should be able to add or remove from that list such that the added or removed users are reflected in the POST for that parameter. In JQuery, after clicking an "Add" button, an ajax call returns a UserModel variable, but a simple .append doesn't add to the list.
The other questions I've seen on this issue deal with Partial Views, but this situation updates the table of UserModel without needing a Partial View. It seems like there should be an easy way to do this. Does anyone know how to add the returned UserModel to the List in JQuery so that the List will be returned to the Post with the added models?
<script>
$("#bUser").on('click', function () {
var $addedRecipient = $("#AddedRecipient");
if ($addedRecipient.val() != null && $addedRecipient.val() != "") {
$.ajax({
type: "GET",
url: '#Url.Action("GetFullRecipient", "Message")',
data: { CompanyID: $("#CompanyID").val(), Employee: $addedRecipient.val() },
success: function (data) {
$("#Recipients").append(data);//Not adding to Recipients (Model.List<UserModel>) - is there a simple solution like this?
var bRow = $('<tr></tr>'),
bCell = $('<td style="display:none"></td>').append(data.UserID);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserFirstName);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserEmail);
bRow.append(bCell);
bCell = $('<td align="center"><input type="button" class="btn btn-info removeRecipient" value="Remove"></td>');
bRow.append(bCell);
$("#bTable tbody").append(bRow);//Works with returned data
$addedRecipient.val("");
},
error: function () {
alert("Recipient could not be added.");
}
});
}
});
</script>
this code worked perfect for me, you just have to go through this list, obviously you have to put the #model directive and a type list Recipient.
#model List<...Models.Recipient>
<input type="button" id="btnAdd" class="btn btn-primary" value="Add"
onclick="myfunction()"/>
<script>
function myfunction() {
$.ajax({
type: 'GET',
contentType:"application/json; charset=utf-8",
url: '#Url.Action("GetFullRecipient","Message")',
data: { CompanyID: $("#CompanyID").val(), Employee:
$addedRecipient.val()},
success: function (response) {
$("#containerData").html(response);
},
error: function (result) {
alert(result);
}
});
}
</script>
<div id="containerData">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Desc_Prod</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>#item.UserID</td>
<td>#item.UserFirstName</td>
<td>#item.UserEmail</td>
<td><a class="btn btn-danger" href="#Url.Action("DeleteRow","Message", new {item.UserID})">Delete</a></td>
</tr>
}
}
</tbody>
</table>
</div>
The answer here followed the link in freedomn-m's comment. Iterate through the Razor table using a for loop, then use a HiddenFor with the model parameter's ID and a CheckBoxFor as the model parameter's selecting field, and have a submit button with a unique name and value. When a button input is clicked and the value fits a given string, loop through the model and add a user that's not there or subtract a user that is there and return to the View.
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered" id="bTable">
<thead>
<tr>
<th style="display:none"></th>
<th style="display:none"></th>
<th class="text-center">Recipient</th>
<th class="text-center">E-mail</th>
<th class="text-center">Select</th>
</tr>
</thead>
<tbody>
#if (Model.Recipients.Any())
{
for (var i = 0; i < Model.Recipients.Count; i++)
{
<tr>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientUserID)</td>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientCorporateID)</td>
<td align="center">#Model.Recipients[i].RecipientName</td>
<td align="center">#Model.Recipients[i].RecipientEmail</td>
<td align="center">#Html.CheckBoxFor(m => m.Recipients[i].RemoveRecipient)</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>

Angularjs ng-repeat error

Using Angularjs I can't do ng-repeat. First ng-repeat is working fine next is not working fine
Html code
<div class="col-xs-12" ng-app="myAns" ng-controller="myCtrl">
<table class="table">
<tr><td ng-repeat="fullname in team1_name">{{fullname}}</td></tr>
<tr><td ng-repeat="strike in team1_strike">{{strike}}</td></tr>
<tr><td ng-repeat="wickets in team1_wickets">{{wickets}}</td></tr>
</table>
</div>
Js code
<script>
var app = angular.module('myAns', []);
app.controller('myCtrl', function($scope, $http, $timeout) {
$timeout(function() {
$http({
url: 'cricketAnswerSuggestionApi.php',
method: "POST",
withCredentials: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function (response) {
$scope.team1_name = response.data.team_1.fullname;
$scope.team1_strike = response.data.team_1.strike_rate;
$scope.team1_wickets = response.data.team_1.wickets;
});
});
});
</script>
JSON response link
https://jsfiddle.net/rijo/aapfa0sL/
Kindly anyone help how to print this value using angularjs ... Thanks for all
Because you have some duplicate data
Use track by $index for team1_strike and team1_wickets
Try this,
<div class="col-xs-12" ng-app="myAns" ng-controller="myCtrl">
<table class="table">
<tr>
<td ng-repeat="fullname in team1_name">{{fullname}}</td>
</tr>
<tr>
<td ng-repeat="strike in team1_strike track by $index">{{strike}}</td>
</tr>
<tr>
<td ng-repeat="wickets in team1_wickets track by $index">{{wickets}}</td>
</tr>
</table>
DEMO

Checking deletion and update ui angular ngResource module

How can I check what is really happening in the below delete function? Every time I delete it says "Success" but the UI doesn't update .
HTML
<md-content >
<div id="main" class="well">
<table cellpadding="20" class="table table-bordered table-striped">
<tr>
<th ng-repeat="(head, value) in models[0]">
<span>{{head}}</span>
</th>
</tr>
<tr ng-repeat="row in models">
<td ng-repeat="(name, value) in row" ng-scope>
<span ng-click="" ng-bind="row[name]"></span>
</td>
<td >
<a target="_self" href="#" ng-click="downlaodId(row)">Downlaod</a>
</td>
<td >
<a target="_self" href="#" ng-click="deleteId(row)" confirmation-needed="Really Delete?">Delete</a>
</td>
</tr>
</table>
</div>
</md-content>
Controller
$scope.deleteId = function (idPassed) {
fileLoadService.delete({ 'id': idPassed.id }, function(successResult) {
alert('Deleted');
}, function (errorResult) {
// do something on error
if (errorResult.status === 404) {
alert('Ooops');
}
});
};
my UI looks like this after click delete
fileLoadservice
app.factory('fileLoadService', ['$resource',
function ($resource) {
return $resource(
"http://jsonplaceholder.typicode.com/todos/:id",
{ id: "#id" },
{ query: { 'method': 'GET', isArray: true }
});
}]);
As you can see from your code:
$scope.deleteId = function (idPassed) {
fileLoadService.delete({ 'id': idPassed.id },function(successResult) {
alert('Deleted');
}, function (errorResult) {
You are doing nothing to the current model, just sending an alert Deleted when you hit the delete button. If you want it to do something else..... you should put that functionality in the code.
For example:
$scope.deleteId = function (idPassed) {
fileLoadService.delete({ 'id': idPassed.id },function(successResult) {
var index = $scope.models.indexOf(idPassed);
$scope.models.splice(index, 1);
alert('Deleted');
}, function (errorResult) {

Categories