When the below form is submitted, and additional entry is created into the database. But the ng-repeat is not getting refreshed.
Any ideas?
html code:
<table class="redTable">
<thead>
<tr>
<th> Domain</th>
<th> Username</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="eachuserconfigdata in userconfigdata track by $index">
<td>
<input type="text" ng-model="eachuserconfigdata.Domain" value="{{ eachuserconfigdata.Domain }}" ng-readonly='!($index == eEditable)' ng-dblclick="eEditable = $index" style="background-color: transparent ; width:80px;border: 0;" />
</td>
<td>
<input type="text" ng-model="eachuserconfigdata.UserName" value="{{ eachuserconfigdata.UserName }}" ng-readonly='!($index == eEditable)' ng-dblclick="eEditable = $index" style="background-color: transparent ; width:80px;border: 0;" />
</td>
</tr>
</tbody>
</table>
<br />
</div>
Javascript
var myApp = angular.module("mymodule", ['ngMaterial']);
var myController = function ($scope, $http, $log) {
$scope.username = "";
$scope.ps = "";
$scope.submit = function () {
//alert($scope.username);
//alert($scope.ps);
$scope.myStyle = { color: 'red' };
var data = {
Domain: $scope.domainname,
UserName: $scope.domainusername,
Password: $scope.domainps
};
$http({
method: 'POST',
//url: 'Login/LoginUser?user=' + $scope.username + '&password=' + $scope.ps,
url: 'Login/UpdateDomainConfiguration',
data: data,
headers: { "Content-Type": "application/json" }
})
.then(function successCallback(response) {
var userid = 0;
$scope.message = response.data;
//$log.info(response);
$scope.GetUserConfigDetails();
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
alert(response.data);
});
}
What you did based on your code is you just saved it to db but never fetched it (not sure about this $scope.GetUserConfigDetails(); though).
What you need to do is after saving it to db, fetch the data again and assign it to your ng-repeat array. Or you can just simply insert the data you've saved to the db into your existing array so that you don't have to fetch again.
Related
I want to send multiple records in the database using javascript in asp.net mvc i tried many different ways but all in vain. here I have the best code which can send the data to the controller but the file is not sending.
I search different ways i have found one is with FormData but i am unable to handle that in this context.
Controller:
public ActionResult SaveAllFeedback(FEEDBACKVM[] fEEDBACKs)
{
try
{
if (fEEDBACKs != null)
{
FEEDBACK fEEDBACK = new FEEDBACK();
foreach (var item in fEEDBACKs)
{
fEEDBACK.DATE = item.DATE;
fEEDBACK.COMMENT = item.COMMENT;
fEEDBACK.STUDENTID = item.STUDENTID;
fEEDBACK.TEACHERID = db.TEACHERs.Where(x => x.EMAIL == User.Identity.Name).FirstOrDefault().ID;
if (item.HOMEWORK != null)
{
fEEDBACK.HOMEWORK = SaveToPhysicalLocation(item.HOMEWORK);
}
db.FEEDBACKs.Add(fEEDBACK);
}
db.SaveChanges();
return Json("Done", JsonRequestBehavior.AllowGet);
}
return Json("Unable to save your feedback! Please Provice correct information", JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json("Unable to save your feedback! Please try again later.", JsonRequestBehavior.AllowGet);
}
}
ViewPage:
<form>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<input name="DATE" id="DATE" type="date" class="form-control" />
</div>
<table class="table table-responsive table-hover" id="table1">
<thead>
<tr class="bg-cyan">
<th></th>
<th>RollNumber</th>
<th>Comment</th>
<th>Homework</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.students)
{
<tr>
<td>
<input name="STUDENTID" type="text" value="#item.Key" hidden="hidden" />
</td>
<td>
<input name="STUDENTROLLNUMBER" type="text" value="#item.Value" class="form-control" readonly="readonly" />
</td>
<td>
<input name="COMMENT" type="text" class="form-control" />
</td>
<td>
<input name="HOMEWORK" type="file" class="form-control" />
</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-10">
#Html.ValidationMessage("ErrorInfo", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="saveButton" type="submit" class="btn btn-danger">Save Attendance</button>
</div>
</div>
</form>
Script:
<script>
//After Click Save Button Pass All Data View To Controller For Save Database
function saveButton(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SaveAllFeedback", "Teacherss")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveButton").click(function (e) {
e.preventDefault();
var formData = new FormData();
var arr = [];
arr.length = 0;
$.each($("#table1 tbody tr"), function () {
//arr.push({
// //DATE: $("#DATE").val(),
// //STUDENTID: $(this).find('td:eq(0) input').val(),
// //COMMENT: $(this).find('td:eq(2) input').val(),
// //HOMEWORK: $(this).find('td:eq(3) input').val()
// });
formData.append("DATE", $("#DATE").val());
formData.append("STUDENTID", $(this).find('td:eq(0) input').val());
formData.append("COMMENT", $(this).find('td:eq(2) input').val());
formData.append("HOMEWORK", $(this).find('td:eq(3) input')[0].files[0]);
});
var data = JSON.stringify({
fEEDBACKs: formData
});
$.when(saveButton (data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
I just want to send multiple records with the file to the database
are you sure you want send the files???? if yes then
Your form tag should be look like this
<form id="yourid" action="youraction" enctype="multipart/form-data">
Form Component
</form>
NOTE:- enctype="multipart/form-data" tag is important
and then controller should be look like this
public ActionResult YourController(FormCollection data)
{
if (Request.Files.Count > 0)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//you can save the file like this
string path = Server.MapPath("~/Yourpath/FileName" + fileName.Substring(fileName.LastIndexOf('.')));
file.SaveAs(path);
//or you can load it to memory like this
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
//use it how you like
}
}
return View();
}
I have an api that gets called on page load. The data from the api is loaded into a table via angular ng-repeat. I also have a javascript function that gets called every 10 seconds that calls the same api for the same dataset. I Would like to know how i can apply the new dataset to the table and replace the old if the dataset changes and how to visually show this change with animation. The code is below.
Table code
<body ng-app="myApp" ng-controller="ScansController">
<div class="bs-example" id="scan-table">
<table id="scansTable" class="table table-striped">
<thead>
<tr>
<th>ScanId</th>
<th>First Name</th>
<th>Last Name</th>
<th>Time Stamp</th>
</tr>
<tr ng-repeat="scan in Scans">
<td>
{{scan.scanId}}
</td>
<td>
{{scan.firstName}}
</td>
<td>
{{scan.lastName}}
</td>
<td>
{{scan.timeStamp}}
</td>
</tr>
</thead>
</table>
</div>
Javascipt interval code
<script>
window.setInterval(function () {
$.ajax({
url: 'api/scans/',
type: 'Get',
dataType: 'json',
success: function (data) {
//Something here
},
error: function () {
alert("something failed");
}
});
}, 10000);
</script>
Angular Code
var myApp = angular.module('myApp', []);
myApp.service('dataService', function ($http) {
this.getData = function () {
return $http({
method: 'GET',
url: '/api/scans/'
});
}
});
myApp.controller('ScansController', function ($scope, dataService) {
$scope.Scans = [];
dataService.getData().then(function (result) {
$scope.Scans = result.data;
console.log(result.data);
});
});
You need to stay inside the current scope.
Setting an interval on a $http call is poison. Use a $timeout inside the success callback to recursively call the next interval.
myApp.controller('ScansController', function ($scope, $timeout, dataService) {
$scope.Scans = [];
function fetchData(){
dataService.getData().then(function (result) {
$scope.Scans = result.data;
$timeout(function(){ fetchData(); },10000);
});
}
fetchData();
});
As far as the table refresh that didnt get addressed, this is how i was able to make it work. I downloaded and applied the animate.css. I then gave the table a starting class to animate it on class load. I then have a function that fetches the array of data on page load and then another that fetches every .5 seconds and compares. If anything has changed, then the class is reapplied and it shows animation.
Angular Ng-Repeat Table
<link href="~/Content/animate.min.css" rel="stylesheet" />
<h1>
Scans
</h1>
<body ng-app="myApp" ng-controller="ScansController" >
<table id="scansTable" class="table table-striped">
<thead>
<tr>
<th>ScanId</th>
<th>First Name</th>
<th>Last Name</th>
<th>Time Stamp</th>
</tr>
<tr ng-repeat="scan in Scans" ng-class-odd="'odd'" ng-class-even="'even'" class="animated bounceIn">
<td>
{{scan.scanId}}
</td>
<td>
{{scan.firstName}}
</td>
<td>
{{scan.lastName}}
</td>
<td>
{{scan.timeStamp}}
</td>
</tr>
</thead>
</table>
Angular Controller
var myApp = angular.module('myApp', []);
myApp.service('dataService', function ($http) {
this.getData = function () {
return $http({
method: 'GET',
url: '/api/scans/'
});
}
});
myApp.controller('ScansController', function ($scope, dataService, $timeout) {
$scope.Scans = [];
$scope.NewScans = [];
function fetchData() {
dataService.getData().then(function (result) {
$scope.Scans = result.data;
$("#scansTable").removeClass('animated bounceIn');
});
}
function fetchNewData() {
dataService.getData().then(function (result) {
$scope.NewScans = result.data;
if ($scope.Scans.length != $scope.NewScans.length)
{
$("#scansTable").addClass('animated bounceIn');
$scope.Scans = $scope.NewScans
}
$timeout(function () { fetchNewData(); }, 500);
});
}
fetchData();
fetchNewData();
});
ANGULAR JS
var App = angular.module('myApp', [])
App.controller('mainController', function ($scope, $http) {
$http.get("/Project/getProjects")
.success(function (result) {
$scope.SuccMsg = "SUCCESS.. ";
$scope.projectList = result;
})
.error(function (Data) {
$scope.ErrMsg = "ERROR.. " + Error;
}) })
CONRTOLLER : PROJECT
public JsonResult getProjects()
{
List<Project> p2 = new List<Project>();
p2 = db.Projects.ToList();
return Json(p2,JsonRequestBehavior.AllowGet);
}
HTML FILE
Project
<div ng-controller="mainController">
#*LIST PROJECT*#
<table id="tbl_Project" class="table-striped">
<tr ng-repeat="item in projectList">
<td>{{item.p_name}}</td>
<td>#*DELETE PROJECT*#
<input id="btn_delete" ng-click="deleteProject(item)" value="X" type="button" />
</td>
</tr>
</table>
<br /><br />
<div style="color:firebrick"><b>{{ErrMsg}}</b></div>
<div style="color:forestgreen"><b>{{SuccMsg}}</b></div> </div>
I Have uploaded my image in local folder using angular file-model and returning the path using json but i am unable to save the path to database. Please help me to solve this issue. I am using .success method to return the response data to a hidden field to store it in database but it shows ERROR:" Cannot read property 'success' of undefined ".
services.js:
service.UploadFile = function (file) {
var fd = new FormData();
fd.append('file', file);
$http.post('/Empdet/UploadFile', fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
})
.error(function () {
});
}
return service;
Controller.js:
$scope.UploadFile = function () {
console.log('UploadFile');
console.log($scope.Empdet.PhotoFile);
EmployeeFactory.UploadFile($scope.Empdet.PhotoFile).success(function (response) {
console.log('response.IsSuccessful');
console.log(response.Data);
$scope.IsSuccessful = response.IsSuccessful;
if ($scope.IsSuccessful) {
$scope.PhotoText = response.Data;
console.log('$scope.PhotoText');
console.log($scope.PhotoText);
$scope.CanClearMessage = true;
} else {
$scope.SuccessMessage = '';
$scope.ErrorMessage = response.ReasonForFailure;
$scope.CanClearMessage = true;
}
}
)};
CreateNewEmployee.cshtml:
<tr>
<td style="text-align: left;">
<label class="labelsytle">
PhotoFile
</label>
</td>
<td style="text-align: left;">
<input class="form-control" type="file" file-model="Empdet.PhotoFile" style="border-radius: 5px;"/>
<td><button class="btn btn-primary" ng-click="UploadFile()" style="border-radius: 5px; font-family: Consolas;">UPLOAD</button></td>
</td>
</tr>
<tr>
#*<td style="text-align: left;">
<label class="labelsytle">
PhotoText
</label>
</td>*#
<td style="text-align: left;">
<input class="form-control" type="hidden" name="search" ng-model="Empdet.PhotoText" placeholder="Enter PhotoText" style="border-radius: 5px;" />
</td>
</tr>
EmpdetController.cs:
[HttpPost]
public ActionResult UploadFile()
{
var file = Request.Files[0];
var path = Path.Combine(Server.MapPath("~/Photos/") + file.FileName);
file.SaveAs(path);
// prepare a relative path to be stored in the database and used to display later on.
path = Url.Content(Path.Combine("~/Photos/" + file.FileName));
// save to db
return Json(path.ToString(), JsonRequestBehavior.AllowGet);
}
Use .then function instead of .success
Replace your .success and .error code block with below code
.then(function (d) {
//Success callback
}, function (error) {
//Failed Callback
alert('Error!');
});
I am using AngularJS and to show products in a table to my users. Here the user can filter the table using categories or other key words. But the user has to be able to edit the product table, like editing product names or prices and these data has to be altered also in my database of course. Now I am using xeditable which works great and I am able to get the productID which I have to change and the function to change the data gets called but that's it. Here can you see my code:
AngularJS
categorieFilter = angular.module("categorieFilter", ["xeditable"])
categorieFilter.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.postname = function ($prodid){
$http.get('api/editproduct/id/$scope.product.name')
.success(function(results){
})
.error(function(data, status){
console.error("Category add error: ", status, data);
});
};
store.getCategories().then(function(data){
$scope.categories = data;
})
store.getProducts().then(function(data){
$scope.products = data;
})
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http, $q){
function _getCategory (){
var deferred = $q.defer();
$http.get('api/categories').success(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function _getProducts (){
var deferred = $q.defer();
var prods = [];
$http.get('api/products').success(function (data) {
for(var i = 0;i<data.length;i++)
{
prods[i] = {id: data[i][0], name: data[i][1], category: data[i][3], price: data[i][2]};
}
deferred.resolve(prods);
})
return deferred.promise;
}
return {
getCategories: _getCategory,
getProducts : _getProducts
};
});
HTML
<div ng-app="categorieFilter" ng-cloak="" ng-controller="catFilter">
<div class="input-group">
<input type="text" name="table_search" class="form-control input-sm pull-right" ng-model="search" placeholder="Search"/>
<div class="input-group-btn">
<button class="btn btn-sm btn-default">
<i class="fa fa-search"></i>
</button>
</div>
</div>
<div>
<input type="submit" class="btn btn-success" style="margin:10px; width:30%;" ng-repeat="cat in categories" ng-click="filterProductsByCats(cat.categoryName)" value="{{cat.categoryName}}">
</div>
<table class="table table-hover">
<tr style="background-color:#ddd;">
<th colspan="4" style="text-align:left; font-size:16px;"> Category </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Product </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Price </th>
</tr>
<tr ng-repeat="product in products | filter:search | orderBy: 'category'">
<td colspan="4">{{product.category}}</td>
<td colspan="4" onaftersave="postname(product.id)" editable-text="product.name">{{product.name}}</td>
<td colspan="4" editable-text="product.price">{{product.price}}</td>
</tr>
</table>
I(m getting error:
ReferenceError: $http is not defined
So what am I doing wrong here? How can I update the required data in my database after changing it in my table using angular and xeditable..?
I updated my controller and function like this and now it works fine:
categorieFilter.controller("catFilter", ["$scope", "$http", "store", function($scope, $http, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
$scope.postname = function ($prodid, $prodname){
alert($prodname);
$http.get('api/editproduct/'+$prodid+'/'+$prodname)
.success(function(results){
})
.error(function(data, status){
console.error("Category add error: ", status, data);
});
};