ng-repeat is not updating when array is pushed inside scope - javascript

i have a web method which is returning json data in every call i am pushing this result into a $scope variable , but inside ng-repeat it is not binding this result . whats wrong with my code . please suggest.
here is my code
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetLocationStockEntries(int LocationId, int ProductId)
{
var jsonText = (dynamic)null;
try
{
if (LocationId > 0)
{
Int64 BusinessUnitId = 0;
using (var db = new repute.Data.ReputEntities())
{
var temp = db.Inventories.Where(p => p.InventoryID == LocationId).FirstOrDefault();
BusinessUnitId = temp == null ? 0 : Convert.ToInt64(temp.BusinessUnitID);
var StockData = db.usp_mvc_InventoryItems_GetAllEntriesByLocation(LocationId, ProductId, BusinessUnitId).Where(x => x.ProjectedQuantityOnHand > 0).ToList();
jsonText = JsonConvert.SerializeObject(new { data = StockData });
}
}
}
catch (Exception ex)
{
}
return jsonText;
}
js :function which is calling this web method evertime and pushing those result into $scope variable
function GetStockEntries(loid, pid)
{
return $http.post(serviceURL + "/GetLocationStockEntries", {LocationId: loid, ProductId: pid }).then(
function success(data, status, headers, config) {
var obj = JSON.parse(data.data.d);
debugger
//$scope.result = obj.data;
$scope.result = obj;
angular.forEach($scope.result, function (key) {
$scope.StockList.push(key);
})
},
function error(data, status, headers, config) {
return data;
});
}
Html:
<table cellpadding="5" cellspacing="0" data-ng-repeat="sTockProduct in ProductList" data-ng-cloak>
<tr>
<td>{{sTockProduct.Name}}
<i class="fa fa-expand" aria-hidden="true" style="color: #000000; text-align: right; margin:5px 0px 0px 10px;" data-ng-click="StockListing(sTockProduct);"></i></td>
</tr>
<tr>
<td>
<table cellpadding="5" cellspacing="0" data-ng-repeat="stockItem in StockList track by $index" data-ng-show = "IsVisible" data-ng-cloak width="100%">
<tr style="border-bottom: 1px solid #ddd; padding-bottom: 5px; margin-bottom: 5px; float: left;">
<td>
<input type="radio" name="groupName" data-ng-value="true" data-ng-model="stockItem.selected[$index]" data-ng-click="onTaskSelect(stockItem,sTockProduct)" />
</td>
<td>
<input type="text" data-ng-model="stockItem.UserInventoryItemID" disabled="" readonly="" style="border: none; background-color: white;">
</td>
<td>
<input type="text" data-ng-model="stockItem.LotNumber" disabled="" readonly="">
</td>
<td>
<!--<input type="text" data-ng-model="stockItem.QuantityOnHand" disabled="" readonly="">-->
<span>{{stockItem.QuantityOnHand}}</span>
<span>{{stockItem.UnitName}}</span>
</td>
<td>
<input type="text" data-ng-model="stockItem.EnteredQuantity" >
</td>
<td>
<input type="text" data-ng-model="stockItem.Description" disabled="" readonly="">
</td>
</tr>
</table>
</td>
</tr>
</table>
Here is the result of json

i guess the problem is with you ng-repeat.try some thing like, do check a condition there if some thing similar in both item. in your inner table do
data-ng-if="stockItem.ProductID== sTockProduct.ProductID"
it should be like:
<table cellpadding="5" cellspacing="0" data-ng-repeat="stockItem in StockList track by $index" data-ng-if="stockItem.ProductID == sTockProduct.ProductID" data-ng-cloak width="100%">
and just a slight modification inside your success:
replace :
$scope.result = obj;
to:
$scope.result = obj.data;

Related

How to pass a list of objects from view

So I'm dynamically creating sections for my objects, where the entered values would be passed to the controller, but I'm having trouble with indexing. Sometimes it works and I think the problem is with my jQuery code, where some some functions are asynchronous and the indexing gets skipped.
The form submit should return a list of KPIs with KPI value, Name and employeeGID. In this example it should return a List of 4 elements, but it returns only one, because it skips 1 and 2 and goes straight to 3
In View HTML code I just have this div to indicate the place to append sections:
<div id="criteriaSections">
</div>
Scripts:
var kpiCount = 0;
function createCriteriaSection(criteria) {
var criterias = #Html.Raw(Json.Serialize(Model.Criterias));
for (var i = 0; i < criterias.length; i++)
{
if (criterias[i].id == criteria.value)
{
var critID = criteria.value;
if (criterias[i].isIndividual)
{
var section =
`<div class="settings">
<fieldset>
<legend>${criteria.text}</legend>
<table id="assignIndividualTable">
<thead>
<tr>
<th style="width:25%; text-align:center">
<label>Employee</label>
</th>
<th style="width: 65%; text-align: center">
<label>KPI Name</label>
</th>
<th style="width: 10%; text-align: center">
<label>Value</label>
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</fieldset>
</div>`;
$("#criteriaSections").append(section);
showIndividualCiteriaEmployees(critID);
}
else
{
var section =
`<div class="settings">
<fieldset>
<legend>${criteria.text}</legend>
<div>
<label>KPI Name: <input type="text" name="KPI[${kpiCount}].Name" class="form-control" required></label>
<label>Value: <input type="text" name="KPI[${kpiCount}].Value" class="form-control" required></label>
<input name="KPI[${kpiCount}].CriteriaID" value="${critID}" type="hidden" />
<input name="employeeGID[${kpiCount}]" class="form-control" value="" type="hidden"/>
</div>
</fieldset>
</div>`;
$("#criteriaSections").append(section);
kpiCount++;
}
}
}
}
function showIndividualCiteriaEmployees(critID) {
var resultLength = 0;
$.post("/KPIs/GetFilteredUsers", { critID: critID }, function (result) {
resultLength = result.length;
var rows = "";
$.each(result, function (i, item) {
rows +=
`<tr>
<td style="width:20%; text-align:center">
<p>${item.text}</p>
<input name="employeeGID[${kpiCount + i}]" class="form-control" value="${item.value}" type="hidden"/>
<input name="KPI[${kpiCount}].CriteriaID" value="${critID}" type="hidden" />
</td>
<td style="width:65%; text-align:center">
<input type="text" name="KPI[${kpiCount}].Name" class="form-control" required/>
</td>
<td style="width:15%; text-align:center">
<input type="text" name="KPI[${kpiCount}].Value" class="form-control" required/>
</td>
</tr>`;
kpiCount++;
});
$("#assignIndividualTable tbody").html(rows);
});
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Date,Name,Value,ID,CriteriaID,Employee")] List<KPI> KPI, List<string> employeeGID)
{
int? id = HttpContext.Session.GetInt32("ID");
if (ModelState.IsValid)
{
for (int i = 0; i < KPI.Count; i++)
{
KPI[i].ManagersId = id.GetValueOrDefault();
KPI[i].Criteria = await _context.Criterias.FirstOrDefaultAsync(x => x.ID == KPI[i].CriteriaID);
if (KPI[i].Criteria.IsIndividual)
{
KPI[i].EmployeeId = _context.Users.First(x => employeeGID[i] == x.GID).ID;
}
}
_context.AddRange(KPI);
await _context.SaveChangesAsync();
return Create();
}
return Create();
}

Send data to controller via Javascript

I have a html table in with razor and I want to send some data from the table to a controller via Javascript.
I tried several different solutions but the data never seems to reach my controller while alerts are being hit. The breakpoints in the controller are never being hit which indicates to me that the data can't reach the controller.
I want the value of #item.PartId and the value of checked to be send to the controller.
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
Javascript
<script type="text/javascript">
$(function ClickHandle() {
$("input[name='IsChecked']").change(function (element) {
var table = document.getElementById("table1");
for (var i = 1; i < table.rows.length; i++) {
var row = table.rows[i];
var lastorder = row.cells[12].firstChild;
var check = lastorder.checked;
if (check) {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = "yellow";
}
else {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = null;
}
//post item.partid and value of check to controller here.
}
});
});
</script>
Controller
[HttpPost]
public ActionResult PostIsChecked(string partId, string isChecked)
{
Part part = new Part
{
id = partId,
isChecked = isChecked
};
//Do stuff
receipt.UpdateCheckedStatus(part);
}
You can try to put a hidden input into <tr></tr>,and set its value with #item.PartId.Then use ajax to post data to action.Here is a demo:
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /><input hidden value=#item.PartId/> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
js:
$("input[name='IsChecked']").change(function () {
var checked = this.checked;
var PartId = $(this).parent().parent().find("input")[0].value;
$.ajax({
type: "POST",
url: "PostIsChecked",
data: { "isChecked": checked, "partId": PartId},
success: function (data) {
}
});
});

Store form data in Local Storage and display in table

How to store form input data? How to get it back and take actions like update, delete and clear?
Storing data using localStorage.setItem();
Getting data using localStorage.getItem();
I am taking user input and trying to save locally using JSON. Want to get data using JSON parse save it in table form. Want to take some actions like ADD Data, DELETE data on click. Clear the table using clear data () function. So I have related functions.
I am new. Didn't understand the logic completely.
HTML FORM:
<form id="form">
<label for="fname">First name:
<input type="text" id="fname" name="fname" placeholder
="name">
</label><br>
<label for="lname">Last name:
<input type="text" id="lname" name="lname"><br>
</label><br>
<button class="btn">Add</button>
<button class="btn">Clear List</button>
</form>
<table id="myTable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th> Action</th>
</tr>
<tableBody id="tabledata">
<tr>
<td>cc </td>
<td> qq </td>
<td><button class="btn">Delete</button></td>
</tr>
</tableBody>
</table>
SCRIPT:
let myfName = document.getElementById("fName").value;
let mylName = document.getElementById("lName").value;
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
itemJsonArray
.push([ myfName, mylName]);
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
update();
// updating inputs in table
function update(){
if(localStorage.getItem('itemJson') == null){
itemJsonArray =[];
localStorage.setItem('itemJeson',
JSON.stringify(itemJsonArray))
}
else{
itemJsonArrayStr =
localStorage.getItem('itemJeson');
itemJsonArry = JSON.parse(
itemJsonArrayStr);
}
let tableData document.getElementById("tabledata");
let str = "";
itemJsonArray.forEach((element, index) => {
str += ` <tr>
<th scope="row"> ${index}</th>
<td> ${element[0]}</td>
<td> ${element [1]}</td>
<td><button class="btn btn-warning btn-sm" onclick = "deleted(${index}" >Delete</button></td>
</tr>`;
});
tablebody.innerHTML = str;
}
let add = document.getElementById("addItem");
add.addEventListener("click", getAndUpdate);
update();
<!DOCTYPE html>
<html>
<body>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>
<div id="result"></div>
<input id="data"></input>
<input type="date" id="date" name="date" value="2018-07-22" min="2018-01-01" max="2018-12-31">
<button onclick="Submit()">Submit</button>
<button onclick="Clear()">Clear</button>
<br><br><br><br><br>
<table id="table">
<tr>
<th>SL. NO</th>
<th>Task Name</th>
<th>Date</th>
</tr>
<tr id ="tbl_data">
</tr>
<tr>
</table>
<script>
// Check browser support
var taskData = [];
var i = null;
function Submit(){
if(taskData.length > 0){
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
var stored = JSON.parse(localStorage.getItem("task"));
stored.push(obj);
}
var data = document.getElementById('data').value;
var date = document.getElementById('date').value;
const obj = { "data": data , "date": date}
taskData.push(obj);
localStorage.setItem("task", JSON.stringify(taskData));
document.getElementById("result").innerHTML = localStorage.getItem("task");
if(i==null){
i= 0;
}
for ( i = i; i < taskData.length; ++i) {
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= i+1;
row.insertCell(1).innerHTML= taskData[i].data;
row.insertCell(2).innerHTML= taskData[i].date;
i=i;
}
}
// Retrieve
</script>
</body>
</html>

Angular JS Method are not defined with Wcf Service

I am consuming Wcf Service in Angular Js Application . My Wcf Service is working and I am trying to display List of User Record from Sql Database . When I run the
application its giving me following errors ...
angular.js:14642 TypeError: Cannot read property 'getAllStudent' of undefined
at GetAllRecords (Registration.js:13)
Here is My Script.js file code ...
/// <reference path="../angular.min.js" />
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService, CRUD_AngularJs_RESTService) {
$scope.OperType = 1;
GetAllRecords();
//To Get All Records
function GetAllRecords() {
var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
promiseGet.then(function (pl) { $scope.User = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Username = "";
$scope.Password = "";
$scopr.Email = "";
}
$scope.createuser = function () {
var User = {
Username: $scope.Username,
Password: $scope.Password,
Email: $scope.Email
};
if ($scope.OperType === 1) {
var promisePost = myService.post(User);
promisePost.then(function (pl) {
$scope.User_Id = pl.data.User_Id;
window.location.href = "/Login/Index";
ClearModels();
}, function (err) {
$scope.msg = "Password Incorrect !";
console.log("Some error Occured" + err);
});
}
}
}]);
app.service("myService", function ($http) {
//Create new record
this.post = function (User) {
var request = $http({
method: "post",
url: "http://localhost:52098/HalifaxIISService.svc/Register",
data: JSON.stringify(User)
});
return request;
this.getAllStudent = function () {
return $http.get("http://localhost:56766/StudentService.svc/GetAllStudent");
}
}
})
Here is HTML Code..
#{
Layout = null;
}
<html data-ng-app="WebClientModule">
<head title="ASAS">
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/RegistrationScript/Registration.js"></script>
</head>
<body>
<table id="tblContainer" data-ng-controller="Web_Client_Controller">
<tr>
<td>
<table style="border: solid 2px Green; padding: 5px;">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th>ID</th>
<th>Username</th>
<th>Password</th>
<th>Emial</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="user in Users">
<tr>
<td></td>
<td><span>{{user.User_Id}}</span></td>
<td><span>{{user.Username}}</span></td>
<td><span>{{user.Password}}</span></td>
<td><span>{{user.Email}}</span></td>
<td>
<input type="button" id="Edit" value="Edit" data-ng-click="get(user)" />
</td>
<td>
<input type="button" id="Delete" value="Delete" data-ng-click="delete(user)" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<div style="color: red;">{{Message}}</div>
<table style="border: solid 4px Red; padding: 2px;">
<tr>
<td></td>
<td>
<span>User ID</span>
</td>
<td>
<input type="text" id="User_Id" readonly="readonly" data-ng-model="User_Id" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Username</span>
</td>
<td>
<input type="text" id="username" data-ng-model="Username" required="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Password</span>
</td>
<td>
<input type="password" id="password" required data-ng-model="Password" require="" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Email</span>
</td>
<td>
<input type="email" id="email" required data-ng-model="Email" require="" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="Createuser" value="Submit" data-ng-click="createuser()" />
<input type="button" id="Clear" value="Clear" data-ng-click="Clear()" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<script src="~/RegistrationScript/Registration.js"></script>
Here is the screen shot when I run the application.
Your service should looks like:
app.service("myService", function ($http) {
//Create new record
this.post = function (User) {
var request = $http({
method: "post",
url: "http://localhost:52098/HalifaxIISService.svc/Register",
data: JSON.stringify(User)
});
return request;
};
this.getAllStudent = function () {
return $http.get("http://localhost:56766/StudentService.svc/GetAllStudent");
}
})
this.getAllStudent should be outside of this.post function.
and in controller:
var promiseGet = myService.getAllStudent();

How to append json values to html[value]

I have Json like this. How to append the json values into html input values.
[{"user_id":"180",
"firstname":"anandhsp",
"lastname":"sp",
"email":"xyz#gmail.com",
"mobile":"9000000000",
"gender":null,
"hashcode":"2XXg3dfyuxjO9C4OvaWw",
"username":"anandhsp21",
"password":"64c20f8bb630eb5cb329fdd609c807b7:J6",
"emailverify":"TRUE",
"company_name":"xxx",
"address":"Chennai",
"city":"Chennai",
"state":"Tamilnadu",
"pincode":"637001",
"phone":"1234567890",
"website":"hello",
"nature":"hello",
"no_employe":"23",
"year":"2015",
"type":"Proprietor",
"authorized_person":"Anandh Sp",
"status":"",
"created":"2015-06-26 10:48:09",
"modified":"2015-06-11 11:24:39",
"logdate":"2015-06-26 05:18:09",
"lognum":"3",
"reload_acl_flag":"0",
"is_active":"1",
"extra":"N;",
"rp_token":null,
"rp_token_created_at":null,
"app_name":"",
"api_key":""}]
Html code
<div id="register_form" class="fieldset subgroupregister_form">
<div class="hor-scroll">
<table class="form-list" cellspacing="0">
<tbody>
<tr class="tr_tag">
<tr class="tr_application_id">
<tr class="tr_customer_id">
<tr class="tr_company_name">
<tr class="tr_address">
<td class="label">
<td class="value">
<input id="address" class=" input-text required-entry" type="text" value="" name="address">
</td>
</tr>
<tr class="tr_city">
<tr class="tr_state">
<tr class="tr_pincode">
<tr class="tr_mobile">
<tr class="tr_phone">
<tr class="tr_website">
<tr class="tr_nature">
<tr class="tr_no_employe">
<tr class="tr_year">
<tr class="tr_type">
<tr class="tr_authorized_person">
<tr class="tr_status">
</tbody>
</table>
</div>
</div>
</div>
I need to append the above values into input value
For example
<input id="address" class=" input-text required-entry" type="text" value="chennai" name="address">
I tried these Codes.But I did't got output.
jQuery('.ac_results ul li').bind('click',function(e)
{
var text = $(this).text();
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {email: text},
dataType:'json',
success: function (data) {
var data = data[0];
$('#address').value = data.address;
$('#city').value = data.city;
$('#state').value = data.state;
$('#pincode').value = data.pincode;
$('#mobile').value = data.mobile;
$('#phone').value = data.phone;
$('#website').value = data.website;
$('#email').value = data.email;
$('#nature').value = data.nature;
$('#year').value = data.year;
$('#no_employe').value = data.no_employe;
$('#type').value = data.type;
$('#authorized_person').value = data.authorized_person;
}
});
});
Thanks In advance
Try val() function:
$('input').val(obj.item);
Check the following example
var obj = { test: 'test' }
$('#add').on('click', function() {
$('#inp').val(obj.test);
});
$('#res').on('click', function() {
alert($('#inp').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="inp" type="hidden" />
<button id="add">Add value</button>
<button id="res">Show input</button>

Categories