Angular UI Switch not retaining enabled when enabled - javascript

i'm a newbie here, hope you could help me with my problem, i am having trouble with retaining the enabled status of my angular ui switch... whenever i refresh the page, it reverts back to disabled . but when i check the database, i could it has updated the value and the selected setting name for the selected ui switch. i want to retain the enabled status of my angular ui switch whenever i enabled it
here is my javascript
(function () {
'use strict';
angular.module('mainApp')
.controller('AdminSettingsController', AdminSettingsController);
function AdminSettingsController(
$scope
,$location
,AdminSettingsService
,$routeParams
) {
$scope.updateSettings = updateSettings;
$scope.getList = getList;
$scope.companyId = $routeParams.companyId;
function updateSettings(key, newStatus) {
AdminSettingsService.saveSetting(newStatus, key, $scope.companyId).then(function (responseObj) {
let data = responseObj.data;
console.log(data.settings)
let success = data.success;
$scope.settings = data.settings;
return data.settings;
});
}
function getList(key){
AdminSettingsService.getSetting(key).then(function (response) {
let data = response.data;
console.log('hardyharhar');
let success = data.success
});
}
}
})();
here is my html
<side-nav active-tab="'admin'"></side-nav>
<head-bar></head-bar>
<div class="br-mainpanel">
<div class="br-pageheader pd-y-15 pd-l-20">
<nav class="breadcrumb pd-0 mg-0 tx-12">
<a class="breadcrumb-item" href="#!/home">Dashboard</a>
<span class="breadcrumb-item active">Admin Settings</span>
</nav>
</div>
<div class="pd-x-5 pd-sm-x-30 pd-t-20 pd-sm-t-2">
<div class="d-flex align-items-center ">
<i class="icon ion-settings tx-54" style="margin-right: 1px;"></i>
<div class="mg-l-20">
<h4 class="tx-18 tx-gray-800 mg-b-5" style="size: 50px; font-weight: bold">Admin Settings</h4>
<span class="mg-b-0">Settings for company.</span>
</div>
<div id="ch5" class="ht-60 tr-y-1"></div>
</div>
</div>
<div class="br-pagebody">
<div class="br-section-wrapper">
<div class="br-pagebody pd-x-20 pd-sm-x-30">
<div class="card bd-0 shadow-base">
<div class="table-responsive">
<table class="table table-striped table-bordered mg-b-0">
<thead>
<th style="width: 10%" class="text-center">Action</th>
<th style="width: 40%" class="text-center">Settings</th>
<th style="width: 10%" class="text-center">Status</th>
</thead>
<tbody>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isReimbursementEnabled', reimbursementStatus)" id="state" name="state" ng-model="reimbursementStatus" class="blue"></switch>
</td>
<td class="text-left">
<h4>Reimbursement</h4>
<p>Allows processor to access reimbursement {{ reimbursementStatus }}.</p>
</td>
<td>
<h4> <span class= "{{ reimbursementStatus ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}">
{{ reimbursementStatus ? "Enabled" : "Disabled"}}
</span>
</h4>
</td>
</tr>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isReportsEnabled', reportsEnabled)" id="state" name="state" ng-model="reportsEnabled" class="blue"></switch>
</td>
<td class="text-left">
<h4 class="">Reports</h4>
<p>Allows processor to access reports.</p>
</td>
<td>
<h4> <span class="{{ reportsEnabled ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}" >
{{ reportsEnabled ? "Enabled" : "Disabled" }}
</span>
</h4>
</td>
</tr>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isAccountsEnabled', accountStatus)" id="state" name="state" ng-model="accountStatus" class="blue"></switch>
</td>
<td class="text-left">
<h4 class="">Accounts</h4>
<p>List of company accounts.</p>
</td>
<td>
<h4><span class="{{ accountStatus ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}" >
{{ accountStatus ? "Enabled" : "Disabled" }}
</span>
</h4>
</td>
</tr>
<tr class="text-center">
<td>
<switch ng-change="updateSettings('isReimbursementRequestLimitEnabled', requestStatus)" id="state" name="state" ng-model="requestStatus" class="blue"></switch>
</td>
<td class="text-left">
<h4 class="">Reimbursement Request Limit</h4>
<p>Sets the reimbursement request limit per year.</p>
</td>
<td>
<h4><span class="{{ requestStatus ? 'badge badge-pill badge-success' : 'badge badge-pill badge-secondary' }}">
{{ requestStatus ? "Enabled" : "Disabled" }}
</span>
</h4>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<foot-bar></foot-bar>
</div>
</div>
and here is my api controller
namespace App\Http\Controllers\Api;
use App\Criteria\LimitOffsetCriteria;
use App\Http\Controllers\Controller;
use App\Models\AdminSettings;
use App\Models\AccountSettings;
use App\Models\Account;
use App\Repositories\AccountRepositoryEloquent;
use App\Repositories\AdminSettingsRepositoryEloquent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class AdminSettingApiController extends Controller
{
private $adminSettingsRepository;
private $accountRepository;
public function __construct(
AdminSettingsRepositoryEloquent $adminSettingsRepo
,AccountRepositoryEloquent $accountRepo
)
{
$this->adminSettingsRepository = $adminSettingsRepo;
$this->accountRepository = $accountRepo;
}
public function saveSetting(Request $request) {
$newStatus = $request->input('newStatus');
$key = $request->input('key');
$companyId = $request->input('companyId');
$result = array(
'success' => false
);
$keyExist = $this->adminSettingsRepository->findByField('setting_name', $key)->first();
log::debug('thisisKeyExist.......................'.json_encode($keyExist));
$newStatusData = [
'setting_name' => $key,
'status' => $newStatus,
'company_id' => $companyId
];
try {
DB::beginTransaction();
if (!$keyExist) {
$newStatus = AdminSettings::create($newStatusData);
}
else {
$updateQuery = AdminSettings::where('setting_name', '=', $key);
$updateQuery->update($newStatusData);
}
$result['success'] = true;
$result['settings'] = $newStatusData;
DB::commit();
} catch (Exception $e) {
Log::error($e);
$result['success'] = false;
$result['messages'] = ['Server has encountered an unexpected error.'];
}
return $result;
}
public function list(Request $request){
$key = $request->input('key');
$result = array(
'success' => false
);
$keySetting = $this->adminSettingsRepository->findByField('setting_name', $key)->first();
$keyList = [];
try {
DB::beginTransaction();
$keyList = $this->adminSettingsRepository::where('status', '=', 1, 'setting_name')->get();
Log::debug('thisIsPrimarykey...................'.json_encode($keyList));
$result['key'] = $key;
$result['success'] = true;
DB::commit();
}
catch (\Exception $e){
Log::error($e);
$result['success'] = false;
}
}
}
hope you could help me thanks a lot! :)

Related

Passing selected dropdown string value from table in view to controller

I'm working on ASP.NET Core web application where I have a table in my view that displays all requests. each record with drop-down populated with all analysts successfully from my database, So the manager can assign the analyst from drop-down then approve the request.
My questions:
Can I implement this using form for each record instead using JavaScript, I mean using only asp tags?
If that should done using JavaScript, Here is my attempt to implement this.
The following code is working only if the Analyst id is integer, but in my case the analyst id is string, so whenever I try to execute this, I got either "null" or "Zero" for the analyst id in the controller. Here is my ViewModel
public class RequestViewModel
{
public IEnumerable<Request> Requests { get; set; }
public IEnumerable<ApplicationUser> AnalystList { get; set; }
public Institution Institution { get; set; }
public string selectedAnalyst { get; set; }
}
Here is my controller
public async Task<IActionResult> ApproveRequest(int id, int Analystid)
{
Request Req = await _db.Request
.Include(c => c.Institution)
.FirstOrDefaultAsync(c => c.Id == id);
if (Req.Type == SD.TypeRegister)
{
Req.Institution.Status = SD.StatusApproved;
Req.Institution.ApprovalDate = DateTime.Now;
Req.Institution.Seats = Req.Seats; // new
Req.Institution.AnalystId = Analystid.ToString(); //Here I want to get the id as string
}
else if (Req.Type == SD.TypeSeat)
{
Req.Institution.Seats += Req.Seats;
}
else if (Req.Type == SD.TypeSubscription)
{
Req.Institution.Seats = Req.Seats;
Req.Institution.Status = SD.StatusApproved;
Req.Institution.ApprovalDate = DateTime.Now;
}
Req.isDone = true;
await _db.SaveChangesAsync();
return await CreateApproval(id, SD.StatusApproved);
}
Here is my View
#model TestApplication.Models.ViewModels.RequestViewModel
#using TestApplication.Extensions
#{
ViewData["Title"] = "Index";
}
<div class="tab-pane fade show active" id="Register" role="tabpanel" aria-labelledby="Register-tab">
Registration Requests
<div>
#if (Model.Requests.Count() > 0)
{
<table class="table table-striped">
<tr class="table-secondary">
<th>
Institution Name
</th>
<th>
Date
</th>
<th>
Actual seat
</th>
<th>
Seats
</th>
<th>
New Seat
</th>
<th>
Choose Analyst
</th>
<th>
Accept / Reject
</th>
<th>
Details
</th>
<th>
</th>
</tr>
#foreach (var item in Model.Requests)
{
#if (item.Type == "Register" && item.Institution.Status == "Pending") #*need one*#
{
<tr>
<td>
#Html.DisplayFor(m => item.Institution.Name)
</td>
<td>
#Html.DisplayFor(m => item.Date)
</td>
<td>
#Html.DisplayFor(m => item.Institution.Seats)
</td>
<td>
#Html.DisplayFor(m => item.ActualSeats)
</td>
<td>
#Html.DisplayFor(m => item.Seats)
</td>
<td>
<select id="selectedAnalyst_#item.Id" asp-for="selectedAnalyst" asp-items=" Model.AnalystList.ToSelectListItem(Model.selectedAnalyst)" class="form-control">
<option selected value="">--- Choose ---</option>
</select>
</td>
<td>
<a class="btn btn-info" asp-controller="Request" asp-action="ApproveRequest" asp-route-id="#item.Id"> accept </a>
<a class="btn btn-info" asp-controller="Request" asp-action="RejectRequest" asp-route-id="#item.Id"> Reject </a>
</td>
<td>
<button type="submit" class="btn btn-success anchorDetail" data-target="#modal-#item.Institution.Id" data-toggle="modal">
View Details
</button>
</td>
<td>
<div class="modal fade" id="modal-#item.Institution.Id" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog-centered modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header bg-success text-light justify-content-center">
<h5 class="modal-title">Request Details</h5>
</div>
<div class="modal-body justify-content-center" id="MyModalContent">
#await Html.PartialAsync("_RequestDetails", item)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">إغلاق</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
}
</table>
}
else
{
<p>No Institutions Exists...</p>
}
</div>
</div>
#section scripts
{
<script>
function accept(id) {
var aid = $('#selectedAnalyst_' + id).val()
location.href = "/Request/ApproveRequest?id=" + id + "&Analystid=" + aid
}
var PostBackURL = '/Request/RequestDetails';
$(function () {
$(".anchorDetail").click(function () {
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
$.ajax({
type: "GET",
url: PostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
cache: false,
datatype: "json",
success: function (data) {
$('#MyModalContent').html(data);
$('#myModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
})
</script>
}
<div class="modal fade" id="MyModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel">
<div id='MyModalContent'></div>
</div>
If you want to pass #item.id and $('#selectedAnalyst_' + id).val() to controller with form,you can do like this.Here is a demo worked(put form outside dropdownlist and button):
<form method="post"
asp-controller="Request"
asp-action="ApproveRequest"
asp-route-id="#item.Id">
<td>
<select id="selectedAnalyst_#item.Id" asp-for="selectedAnalyst" class="form-control">
<option selected value="">--- Choose ---</option>
<option selected value="1">1</option>
<option selected value="2">2</option>
<option selected value="3">3</option>
</select>
</td>
<td>
<button type="submit">Accept</button>
</td>
</form>
Controller(change Analystid to selectedAnalyst,so that you can bind asp-for="selectedAnalyst",and if you want to get string parameter,you can change it to string selectedAnalyst):
public IActionResult ApproveRequest(int id,string selectedAnalyst)
{
return Ok();
}
result:

How to Call Partial View with Asp.Net Mvc

I need to search on the database, and load only the View, and not refresh the entire page. A function in Js calls my method on the controller, when clicking on search, and the controller returns the View.
function Pesquisa()
{
let campo = document.getElementsByName("campo");
let pesquisa = document.getElementsByName("EdtPesquisa");
let condicao = document.getElementsByName("pesquisa");
let scampo = Array();
let spesquisa = Array();
let scondicao = Array();
let sNomeGrid = ($(this).find("a").text());
for (var indice = 0; indice < pesquisa.length; indice++)
{
string = pesquisa[indice].value;
if (string.trim() != "")
{
scampo[indice] = campo[indice].id;
scondicao[indice] = condicao[indice].value;
spesquisa[indice] = pesquisa[indice].value;
}
}
window.location.href = "/MenuPrincipal/RetornarView?sNomeGrid=" + "Unidade" + "&listacampo=" + scampo + "&listacondicao=" + scondicao + "&listapesquisa=" + spesquisa;
Controller
public IActionResult RetornarView(string sNomeGrid, List<string> listacampo, List<string> listacondicao, List<string> listapesquisa)
{
var sWhere = "";
if (listacampo.Count > 0)
{
Pesquisa _Pesquisa = new Pesquisa();
sWhere = _Pesquisa.Pesquisar(listacampo, listacondicao, listapesquisa);
}
if (sNomeGrid == "Unidade")
{
var listaunidade = _UnidadeRepositorio.ListarMenu(sWhere);
return View("Unidade", listaunidade);
}
return View("MenuPrincipal");
}
View
#model IEnumerable<ApesWeb.Models.Classes.Unidade>
<div class="tabela-responsive">
<table id="tabela" class="tabela tabela-hover"
data-toggle="table">
<thead>
<tr>
<th id="idunidade" name="campo">#Html.DisplayNameFor(model => model.idunidade)</th>
<th id="sdescricao" name="campo">#Html.DisplayNameFor(model => model.sdescricao)</th>
<th id="sunidade" name="campo">#Html.DisplayNameFor(model => model.sunidade)</th>
<th id="sdigitavolume" name="campo">#Html.DisplayNameFor(model => model.sdigitavolume)</th>
<th id="spadraosistema" name="campo">#Html.DisplayNameFor(model => model.spadraosistema)</th>
</tr>
<tr>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa"/>
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
<th>
<div class="inputWithIcon">
<select name="pesquisa" />
<input type="text" name="EdtPesquisa"/>
<i class="fa fa-search" aria-hidden="true" onclick="Pesquisa()"></i>
</div>
</th>
</tr>
</thead>
<tbody>
#foreach (var Unidade in Model)
{
<tr>
<td>
#Html.DisplayFor(modelitem => Unidade.idunidade)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.sdescricao)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.sunidade)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.sdigitavolume)
</td>
<td>
#Html.DisplayFor(modelitem => Unidade.spadraosistema)
</td>
</tr>
}
</tbody>
</table>
Returns the View with the list to fill the Table, but in this process the entire page is refreshed.
You can use one of the following methods according to your needs:
Method I: If you want to use ViewData, try this:
#Html.Partial("~/PathToYourView.cshtml", null,
new ViewDataDictionary { { "VariableName", "some value" } })
And to retrieve the passed in values:
#{
string valuePassedIn = this.ViewData.ContainsKey("VariableName") ?
this.ViewData["VariableName"].ToString() : string.Empty;
}
Method II: If you just render a partial with just the partial name:
#Html.Partial("_SomePartial", Model)
Method II: Render PartialView using jQuery Ajax call:
Firstly wrap your body content in a div and assign any id to it in _Layout page:
<div id="div-page-content" class="page-content">
#RenderBody()
</div>
Here is the menu item used for rendering PartialView in _Layout page:
<ul class="sub-menu">
<li class="nav-item ">
<a href="#" onclick="renderPartial(event, 'Account', '_Register')" class="nav-link">
<span class="title">Create New User</span>
</a>
</li>
</ul>
Define the javascript function for click event in _Layout page:
function renderPartial(e, controller, action) {
e.preventDefault();
e.stopPropagation();
var controllerName = controller;
var actionName = action;
if (String(actionName).trim() == '') {
return false;
}
if (typeof (controllerName) == "undefined") {
return false;
}
var url = "/" + controllerName + "/" + actionName;
////Open url in new tab with ctrl key press
//if (e.ctrlKey) {
// window.open(url, '_blank');
// e.stopPropagation();
// return false;
//}
$.ajax({
url: url,
data: { /* additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data) {
var requestedUrl = String(this.url).replace(/[&?]X-Requested-With=XMLHttpRequest/i, "");
if (typeof (requestedUrl) == "undefined" || requestedUrl == 'undefined') {
requestedUrl = window.location.href;
}
// if the url is the same, replace the state
if (typeof (history.pushState) != "undefined") {
if (window.location.href == requestedUrl) {
history.replaceState({ html: '' }, document.title, requestedUrl);
}
else {
history.pushState({ html: '' }, document.title, requestedUrl);
}
}
$("#div-page-content").html(data);
},
error: function (data) { onError(data); }
});
};
Define your PartialView as shown below:
<div>
... partial view content goes here >
</div>
Add the Action metdod to the Controller as shown below:
[HttpPost]
[AllowAnonymous]
public PartialViewResult _Register(/* additional parameters */)
{
return PartialView();
}

Table TH not displaying correctly after onchange evernt fires

So I'm trying to hide the Company Name <th> column when the employee drop down is selected.
I have this jQuery function that I've been trying to figure out for sometime now and cant seem to get it working. I've tried to walk though script with FF debugger but nothing happens, with no errors. Im kind of lost on where to take it from here.
DropDown
#using (Html.BeginForm())
{
#Html.DropDownList("SearchStatus", new SelectList(ViewBag.SearchStatusList, "Value", "Text", ViewBag.SelectedItem), new { #class = "form-control", #onchange = "form.submit();" })
}
jQuery
<script type="text/javascript">
$("#SearchStatus").on("change", function () {
if ($("#SearchStatus option:selected").val() == 0) {
$("#hidden_div").hide();
} else {
$("#hidden_div").show();
}
});
VIEW
#model PagedList.IPagedList<Login.Models.EditProfile>
#using PagedList.Mvc;
#{
ViewBag.Title = "Pending Accounts";
}
<link href="~/Content/PagedList.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<style>
... deleted CSS that was here
</style>
<h2>Pending Accounts</h2>
#using (Html.BeginForm())
{
#Html.DropDownList("SearchStatus", new SelectList(ViewBag.SearchStatusList, "Value", "Text", ViewBag.SelectedItem), new { #class = "form-control", #onchange = "form.submit();" })
}
<br />
<table class="table grid">
<tr>
<th>
<b>Options</b>
</th>
<th>
First Name:
</th>
<th>
Last Name:
</th>
<th>
Email:
</th>
<th>
Phone Number:
</th>
<th id="hidden_div" style="display: none;">
Company Name:
</th>
<th></th>
</tr>
#foreach (var item in Model.ToList())
{
<tr>
<td>
<div class="btn-group">
<button type="button" id="bootstrap-ok" class="btn btn-default btn-sm icon-success">
<span class="glyphicon glyphicon-ok "></span>
</button>
<button type="button" id="bootstrap-danger" class="btn btn-default btn-sm icon-danger">
<span class="glyphicon glyphicon-remove "></span>
</button>
</div>
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhoneNumber)
</td>
#if (item.CompanyName != null)
{
<td>
#Html.DisplayFor(ModelItem => item.CompanyName)
</td>
}
</tr>
}
</table>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("PendingAccounts", new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
#if (Request.IsAuthenticated)
{
using (Html.BeginForm("Logout", "User", FormMethod.Post, new { id = "logoutForm" }))
{
Logout
}
}
<script type="text/javascript">
$("#SearchStatus").on("change", function () {
if ($("#SearchStatus option:selected").val() == 0) {
$("#hidden_div").hide();
} else {
$("#hidden_div").show();
}
});
you can get the value of the dropdown by using $(yourDropdown).val() and not selecting the options. So try this:
$("#SearchStatus").on("change", function () {
if ($("#SearchStatus").val() == 0) {
$("#hidden_div").hide();
} else {
$("#hidden_div").show();
}
});

AngularJS - Pagination Example with Logic like Google

I have tried to implement this paging solution that I found online from this link:
http://jasonwatmore.com/post/2016/01/31/AngularJS-Pagination-Example-with-Logic-like-Google.aspx
I think the issue is in the way the functions are called, because the setPage function gets called before I have all my data so it does not know how many total items there are to be displayed etc. Can someone take a quick look and see what I'm doing wrong?
function HistoryController($window, $scope, $modal, $state, toaster, PagerService, HistoryFactory, $timeout) {
var vm = this;
vm.uploads = [];
vm.includeCancelled = false;
vm.uploadDataModal = {};
vm.pager = {};
vm.setPage = setPage;
activate();
function activate() {
getHistory();
vm.setPage(1);
}
function setPage(page) {
if (page < 1 || page > vm.pager.totalPages) {
return;
}
// get pager object from service
vm.pager = PagerService.GetPager(vm.uploads.length, page);
// get current page of items
vm.items = vm.uploads.slice(vm.pager.startIndex, vm.pager.endIndex + 1);
}
function getHistory() {
HistoryFactory.getHistory(vm.includeCancelled).then(
function(response) {
_.each(response.data, function(upload) {
upload.inProgress = upload.status && ['INPROGRESS','NEW'].indexOf(upload.status.statusCd.trim()) > -1;
});
vm.uploads = response.data;
if($state.params.reupload){
uploadProductionData();
$state.params.reupload = false;
}
});
}
Here is the html
<div class="chrthdr" ui-view="header"></div>
<div id="userResults">
<div class="card card-full-width">
<div class="card-header dark-blue">
<a class="card-config" data-toggle="uploadHistory" data-placement="left"><i class="glyphicon glyphicon-info-sign"></i></a>
<div class="card-title">Data History</div>
</div>
<div class='form-horizontal range-date' style="overflow-y: auto;">
<form>
<div class="panel-body">
<div>
<span class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; margin-right: 5px" type="button" ng-click="vm.uploadProductionData()">Upload Data</span>
<label>
<input type="checkbox" ng-model="vm.includeCancelled">Include removed executions
</label>
<!--<span class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; margin-left: 5px" type="button" ng-click="vm.viewTemplates()">Download Template</span>-->
</div>
<div>
<table class="table">
<tr>
<th>Upload Date</th>
<th>Product</th>
<th>Comments</th>
<th>Template</th>
<th>Last Updated By</th>
<th>Last Updated</th>
<th>Status</th>
<th>Actions</th>
</tr>
<tr ng-repeat="upload in vm.uploads | orderBy:'uploadDate':true">
<td style="white-space: nowrap;">{{upload.uploadDate}}</td>
<td>{{upload.product}}</td>
<td style="white-space: nowrap;">{{upload.comments}}</td>
<td style="white-space: nowrap;">{{upload.templateName}}</td>
<td style="white-space: nowrap;">{{upload.lastUpdatedByUser}}</td>
<td style="white-space: nowrap;">{{upload.lastUpdateDate}}</td>
<td style="white-space: nowrap;">{{upload.status.statusName}}</td>
<td>
<button class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; " ng-hide="upload.status.statusCd === 'NEW' || upload.status.statusCd === 'ERROR'" ng-click="vm.loadStagingPage(upload.dataLoadExecutionId, upload.product, upload.status)">View</button>
<span class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; " type="button" ng-click="vm.cancelDataExecution(upload.dataLoadExecutionId)" ng-show="upload.inProgress || upload.status.statusCd === 'ERROR'">Remove</span>
</td>
</tr>
</table>
</div>
<div class="text-center">
<ul ng-if="vm.pager.pages.length" class="pagination">
<li ng-class="{disabled:vm.pager.currentPage === 1}">
<a ng-click="vm.setPage(1)">First</a>
</li>
<li ng-class="{disabled:vm.pager.currentPage === 1}">
<a ng-click="vm.setPage(vm.pager.currentPage - 1)">Previous</a>
</li>
<li ng-repeat="page in vm.pager.pages" ng-class="{active:vm.pager.currentPage === page}">
<a ng-click="vm.setPage(page)">{{page}}</a>
</li>
<li ng-class="{disabled:vm.pager.currentPage === vm.pager.totalPages}">
<a ng-click="vm.setPage(vm.pager.currentPage + 1)">Next</a>
</li>
<li ng-class="{disabled:vm.pager.currentPage === vm.pager.totalPages}">
<a ng-click="vm.setPage(vm.pager.totalPages)">Last</a>
</li>
</ul>
</div>
</div>
</form>
</div>
</div>
This is a very common mistake of not understanding asynchronous calls.
HistoryFactory.getHistory(vm.includeCancelled).then({}) is async, meaning that it will make the call and then continue executing code after the async call. When the async call has finished, the code inside .then({}) will then execute which could be 5 milliseconds or 5 seconds.
So here:
function activate() {
getHistory(); // async call, doesn't wait
vm.setPage(1); // executed immediately after, data not ready
}
Needs to be:
function activate() {
getHistory();
}
And changegetHistory() to:
function getHistory() {
HistoryFactory.getHistory(vm.includeCancelled).then(
function(response) {
_.each(response.data, function(upload) {
upload.inProgress = upload.status && ['INPROGRESS','NEW'].indexOf(upload.status.statusCd.trim()) > -1;
});
vm.uploads = response.data;
if($state.params.reupload){
uploadProductionData();
$state.params.reupload = false;
}
// Now call setPage after data is finished
vm.setPage(1);
});
}

How to modify and update data table row in angular js?

I m learning of angular js and i have found i issue .
I m creating a new projects .
i have some button edit , add, remove,
if i click to my edit button than show all field but i want to show only current field than i click to update update this filed .
My code is here
Anguar
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
HTML Code is
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>
var app = angular.module('addApp', []);
app.controller('modifyCtrl', ['$scope', function($scope){
$scope.tabelsData= [
{'name':'rohit', 'dob':'15-august-1985', 'emailId':'rohit#rohit.com', 'phone':'9999999999', 'address':'Delhi Rohini', 'id':'0' },
{'name':'aman', 'dob':'26-july-1975', 'emailId':'haryanat#hr.com', 'phone':'9874563210', 'address':'Haryana Sonepat', 'id':'1' },
{'name':'devraj', 'dob':'27-march-1980', 'emailId':'punjab#punjab.com', 'phone':'7410258963', 'address':'Punjab AmritSar', 'id':'2' }
];
$scope.modify = function(tableData){
$scope.modifyField = true;
$scope.viewField = true;
};
$scope.update = function(tableData){
$scope.modifyField = false;
$scope.viewField = false;
};
}]);
table td, table th{
border:solid 1px red;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="addApp">
<div class="wraper" ng-controller="modifyCtrl">
<table>
<thead>
<tr>
<th>Name:</th>
<th>Date Of Birth</th>
<th>Email Id</th>
<th>Phone No.</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tableData in tabelsData"><form>
<td>
<div ng-hide="viewField">{{tableData.name | uppercase}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.dob}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.emailId}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.phone}}</div>
<div ng-show="modifyField"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="viewField">{{tableData.address}}</div>
<div ng-show="modifyField">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="viewField" ng-click="modify(tableData)">Modify</button>
<button ng-show="modifyField" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td></form>
</tr>
</tbody>
</table>
</div>
</div>
If you only want one row to show the inputs on clicking its respective modify button you have two options:
1) Attach booleans to each of the JSON indexes of the tabelsData array.
2) Make a mirror array that houses these booleans.
Having two separate booleans in this case is useless, because each one is being treated on a toggle basis:
Here is the core code for doing approach number two since I assume you want your data to remain the same:
JS:
$scope.editingData = {};
for (var i = 0, length = $scope.tabelsData.length; i < length; i++) {
$scope.editingData[$scope.tabelsData[i].id] = false;
}
$scope.modify = function(tableData){
$scope.editingData[tableData.id] = true;
};
$scope.update = function(tableData){
$scope.editingData[tableData.id] = false;
};
Html:
<tbody>
<tr ng-repeat="tableData in tabelsData">
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.name | uppercase}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.name" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.dob}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.dob" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.emailId}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.emailId" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.phone}}</div>
<div ng-show="editingData[tableData.id]"><input type="text" ng-model="tableData.phone" /></div>
</td>
<td>
<div ng-hide="editingData[tableData.id]">{{tableData.address}}</div>
<div ng-show="editingData[tableData.id]">
<textarea ng-model="tableData.address"></textarea>
</div>
</td>
<td>
<button ng-hide="editingData[tableData.id]" ng-click="modify(tableData)">Modify</button>
<button ng-show="editingData[tableData.id]" ng-click="update(tableData)">Update</button>
<button ng-hide="viewField">Add</button>
<button ng-hide="viewField">Remove</button>
</td>
</tr>
</tbody>
I made an example:
http://plnkr.co/edit/lXq1WB
Here is an example in Angular2, (this will NOT work for AngularJS!)
fichier.html:
<ng2-toasty [position]="'top-left'"></ng2-toasty>
<label for="trainingInput" class="mr-2">{{ 'LABEL.FORMATION' | translate }} :</label>
<table class="table table-hover table-striped table-sortable table-bordered">
<thead>
<tr>
<th *ngFor="let column of columns" [class]="selectedClass(column.variable)" (click)="changeSorting(column.variable)" translate>
{{column.display}}
</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let object of data | orderBy : convertSorting(); let rowIndex = index">
<td *ngFor="let column of columns" class="{{column.variable}}-td">
<div *ngIf="!toUpdates[object['id']]" >{{object[column.variable] | format: column.filter}}</div>
<div *ngIf="toUpdates[object['id']]"><input type="text" [(ngModel)]="object[column.variable]" ></div>
</td>
<td class="text-center">
<i *ngIf="!toUpdates[object['id']]" class="fa fa-pencil-square-o edit-formation" aria-hidden="true" (click) = "editFormation(object)"></i>
<i *ngIf="toUpdates[object['id']]" class="fa fa-check-square-o save-edit-form" (click)="updateFormation(object)"></i>
<i class="fa fa-times" aria-hidden="true" (click)="deleteFormation(object['id'])"></i>
</td>
</tr>
<tr [hidden]="isDisabled()">
<td><input type="text" class="form-control" placeholder="Année" #years></td>
<td><input type="text" class="form-control" placeholder="Formation" #label></td>
<td><input type="text" class="form-control" placeholder="Durée" #duration></td>
<td class="text-center align-middle">
<i class="fa fa-plus-circle fa-2x" (click)="addFormation(years.value, label.value, duration.value)"></i>
</td>
</tr>
</tbody>
</table>
fichier.ts:
import {Component, Injector, Input, OnChanges, OnInit} from '#angular/core';
import { Http, Headers, RequestOptions, URLSearchParams } from '#angular/http';
import DynamicComponent from '../dynamic-component';
import Formation from './formation';
import {ToastyService, ToastyConfig, ToastOptions, ToastData} from 'ng2-toasty';
#Component({
moduleId: module.id,
selector: 'formations-selector',
templateUrl: './formations-template.html',
styleUrls: ['./formations-template.css'],
})
export default class FormationsComponent{
candidate: any = null;
listFormations: any = null;
candidateDetails: any = null;
columns: any[];
sort: any;
data: any[];
toUpdates: {};
constructor(private injector: Injector, private http: Http,private toastyService: ToastyService, private toastyConfig: ToastyConfig) {
this.candidateDetails = this.injector.get('candidateDetails');
this.candidate = this.candidateDetails.candidate;
this.listFormations = this.candidateDetails.listFormations;
this.columns = this.listFormations.columns;
this.sort = this.listFormations.sort;
this.data = this.listFormations.data;
this.toastyConfig.theme = 'material';
this.toUpdates = {};
}
ngAfterViewInit(){
$(document).ready(function() {
/*
$('.edit-formation').click(function () {
var dad = $(this).parent().parent();
dad.find('td .duration-span').hide();
dad.find('td.duration-td').append('<input type="text" class="form-control" placeholder="Durée" value="'+dad.find('td .duration-span').html()+'" id = "duration-update" #durationu>');
dad.find('td .label-span').hide();
dad.find('td.label-td').append('<input type="text" class="form-control" placeholder="Formation" id="label-update" value="'+dad.find('td .label-span').html()+'" #labelu>');
dad.find('td .years-span').hide();
dad.find('td.years-td').append('<input type="text" class="form-control" placeholder="Année" id="years-update" value="'+dad.find('td .years-span').html()+'" #yearsu>');
dad.find('td.years-td').append('<i class="fa fa-check-square-o save-edit-form hidden" (click)="updateFormation(1, years.value, label.value, durationu)"></i>');
dad.find('td .edit-formation').addClass("hidden");
dad.find('td .save-edit-form').removeClass("hidden");
});
*/
/*
$('.save-edit-form').click(function () {
var dad = $(this).parent().parent();
dad.find('td .save-edit-form').addClass("hidden");
dad.find('td .edit-formation ').removeClass("hidden");
dad.find('td .duration-span').show();
$('#duration-update').remove();
dad.find('td .label-span').show();
$('#label-update').remove();
dad.find('td .years-span').show();
$('#years-update').remove();
});
*/
});
}
//Action déclenché lors d'un changement de société du candidat : on met à jour la liste des métiers associés
onChangeCompaniesInput(value) {
}
isDisabled(isDisabled) {
//return (isDisabled || !this.candidateDetails.isUserAuthorized) ? true : false;
}
selectedClass(columnName): string{
return columnName == this.sort.column ? 'sort-' + this.sort.descending : '';
}
changeSorting(columnName): void{
var sort = this.sort;
if (sort.column == columnName) {
sort.descending = !sort.descending;
} else {
sort.column = columnName;
sort.descending = false;
}
}
convertSorting(): string{
return this.sort.descending ? '-' + this.sort.column : this.sort.column;
}
onChangeMainFormaion(value): void{
console.log(value);
}
deleteFormation(idFormation): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
this.http.post('/api/formations/'+idFormation+'/deleteFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait supprmié avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
editFormation(tableData): void{
this.toUpdates[tableData['id']]= true;
}
updateFormation(tableData): void {
this.toUpdates[tableData['id']]= false;
console.log(tableData);
}
addFormation(years: string, label: string, durration: string, main: boolean = false): void{
let headers = new Headers('Content-Type', 'application/json');
let params: URLSearchParams = new URLSearchParams();
params.append('years', years);
params.append('label', label);
params.append('durration', durration);
params.append('main', main);
//let formation = new Formation(years, label, durration, false);
return this.http.post('/api/formations/'+this.candidate.id+'/addFormation', params).toPromise()
.then(
res =>
{
if(res.status == 200){
this.toastyService.success({
title: "Success",
msg: "La formation a etait ajouter avec Succès",
showClose: true,
timeout: 5000,
theme: 'default',
});
}else{
this.toastyService.error({
title: "Error",
msg: "Une erreur est survenue, veuillez réessayer ultérieurement",
showClose: true,
timeout: 5000,
theme: 'default',
});
}
}
).catch(this.handleError);
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Promise.reject(errMsg);
}
}

Categories