I am programming a crud application with a creation date. when I add a new object, the date is saved on the database with a good format :
Database
Now when the date is displayed on the table, it shows me like this :
enter image description here
I found a solution to show it as a good format with {{Rec.Date.slice(6,-2) | date:'dd/MM'}}
The issue is that when I tried to add a datepicker to make a seach with the date variable, the search does not match anything even if I give it a date already existed on the base. I am pretty sure that the issue is with date format but I don't find any solution to format it when the save of a new reclamation is done.
reclamations-by-date-controller.js :
(function () {
'user strict';
angular
.module('app')
.controller('ReclamationsByDateController', ['$scope', 'ReclamationsByDateService', function
($scope, ReclamationsByDateService) {
// Call GetAllReclamations function to init the table
GetAllReclamations();
// Get reclamation list function
function GetAllReclamations() {
var getRecData = ReclamationsByDateService.getReclamations();
getRecData.then(function (reclamation) {
$scope.reclamations = reclamation.data;
}, function () {
alert('Error in getting reclamations records');
});
}
$scope.changeSelect = function (dt) {
$scope.changeDate = moment(dt).format("DD/MM/YYYY");
}
$scope.today = function () {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function () {
$scope.dt = null;
};
$scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.dateOptions = {
formatYear: 'yyyy',
startingDay: 1
};
$scope.formats = ['dd/MM/yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];
}])
.service('ReclamationsByDateService', ['$http', function ($http) {
// Get Reclamations
this.getReclamations = function () {
return $http.get("/Reclamations/ReclamationsList");
};
}]);
})();
ReclamationsByDate.cshtml :
<div ng-controller="ReclamationsByDateController">
<pre>Please select a date: <em>{{dt | date:'fullDate' }}</em></pre>
<h4>DatePicker</h4>
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="date" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-
open="opened" min-date="minDate" max-date="'2015-06-22'" ng-change="changeSelect(dt)" date-
disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)">Search</button>
</span>
</p>
</div>
</div>
<pre>{{changeDate}}</pre>
<table class="table table-striped" show-filter="true" id="tblReclamations" style="width:100%">
<thead>
<tr>
<th>
Id
</th>
<th>
Date
</th>
<th>
Title
</th>
<th>
Status
</th>
<th>
Responsible
</th>
<th>
Comment
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="Rec in reclamations | filter: {Date:changeDate}" ng-class-odd="'odd'" ng-
class-even="'even'" ng-style="{ 'background-color' : (Rec.Status == 'Pending') ? 'orange' : 'null'
}">
<td>{{Rec.RecId}}</td>
<td style="font-size: small; color:red;"><strong>{{Rec.Date}}</strong></td>
<td style="font-size: medium;"><strong>{{Rec.Title}}</strong></td>
<td style="font-size: small;"><strong>{{Rec.Status}}</strong></td>
<td>{{Rec.Responsible}}</td>
<td style="font-size: small;"><strong>{{Rec.Comment}}</strong></td>
</tr>
</tbody>
</table>
</div>
<script src="~/Scripts/app/controllers/reclamations-by-date-controller.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.js"></script>
<script>
</script>
_Layout.cshtml :
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet"
href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.all.css"
type="text/css" media="screen">
<link rel="stylesheet" href="/Content/bootstrap-datetimepicker.css" />
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet">
<script src="~/Scripts/modernizr-2.8.3.js"></script>
<script src="~/Scripts/jquery-3.0.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="/scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="/scripts/moment.min.js"></script>
<script type="text/javascript" src="/scripts/bootstrap-datetimepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.5.0/jszip.js"></script>
<script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">
</script>
<script src="~/Scripts/angular.min.js"></script>
<script src="//cdn.jsdelivr.net/angular.ngtable/0.3.3/ng-table.js"></script>
<script src="~/Scripts/angular-route.min.js"></script>
<script src="~/Scripts/app/app.js"></script>
Thank you !
The problem is with your filter
ng-repeat="Rec in reclamations | filter: {Date:changeDate}"
You need to pass to Angular filter a Date object, but changeDate is not (since you set it to a custom string on your datepicker handler). That's why the search fails.
Change your handler as follows:
$scope.changeSelect = function (dt) {
$scope.changeDate = dt;
}
you can try this
<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
You could make use of customFilter to format any dates.
I'm using momentjs library here.
(function () {
'use strict';
angular
.module('app.core') // use your module name here
.filter('humanizeFilter', ['moment', function (moment) {
return function (input) {
return moment(input).format('MMM D, YYYY, HH:mm');
};
}
]
);
})();
Then in your template, you can use as below:
<span>{{1592585639000 | humanizeFilter}}</span><br>
Hope this helps!!
Related
Currently I am working on an ASP.NET Core MVC project. I want to implement in-line editing. Therefore tha plan is to pass the data in a JSON format to the controller and save it. Problem is, I am unable to do so.
My Controller: DenoProfileController
[HttpPost]
public ActionResult Update(DenoProfile denoprofile)
{
DenoProfile emp = db.DenoProfile.Single(em => em.DenoProfileID == denoprofile.DenoProfileID);
emp.NetworkNumber = denoprofile.NetworkNumber;
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("IndexDenoProfile", new { id = 0 });
}
My View:
#model IEnumerable<CRUD_Profile_Creation.Models.ProfileCreationContext>
#{
ViewData["Title"] = "DenoProfile";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('.edit-mode').hide();
$('.edit-user, .cancel-user').on('click', function () {
var tr = $(this).parents('tr:first');
tr.find('.edit-mode, .display-mode').toggle();
});
$('.save-user').on('click', function () {
var tr = $(this).parents('tr:first');
var NetworkNumber = tr.find("#NetworkNumber").html();
//Creating Employee JSON object
var EmployeeModel =
{
"NetworkNumber": NetworkNumber,
};
console.log(EmployeeModel.value);
//Posting Employee object to controller's Update action method
$.ajax({
url: "DenoProfile/Update",
data: JSON.stringify(EmployeeModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
tr.find('.edit-mode, .display-mode').toggle();
alert('Record updated Successfully!!');
}
});
});
$('.edit-user').on('click', function () {
var tr = $(this).parents('tr:first');
var NetworkNumber = tr.find("#NetworkNumber").html();
tr.find("#lblNetworkNumber").text(NetworkNumber);
});
})
</script>
<div class="container-fluid" align="center" justify-content="center" style="background-color:white;">
<h1>List of Clients</h1>
<a class="btn btn-success" asp-area="" asp-controller="DenoProfile" asp-action="AddDenoProfile">Profile Creation</a>
<br />
<br />
<table class="table-striped table-bordered">
<thead>
<tr align="center" justify-content="center">
<th>
Deno Profile ID
</th>
<th>
Network Number
</th>
</tr>
</thead>
<tbody>
#foreach (var item in (IEnumerable<CRUD_Profile_Creation.Models.DenoProfile>)ViewBag.DenoProfile)
{
<tr align="center" justify-content="center">
<td>
#Html.DisplayFor(modelItem => item.DenoProfileID)
</td>
<td>
<div class="display-mode" id="lblNetworkNumber">
#Html.DisplayFor(modelItem => item.NetworkNumber)
</div>
<div class="edit-mode">
<input type="text" id="NetworkNumber" value="#item.NetworkNumber" class="edit-mode" />
</div>
</td>
<td>
<button class="edit-user display-mode">Edit</button>
<button class="save-user edit-mode">Save</button>
<button class="cancel-user edit-mode">Cancel</button>
<button class="btn btn-danger"> #Html.ActionLink("Delete Deno Profile", "DeleteDenoProfile", new { id = item.DenoProfileID })</button>
</td>
</tr>
}
</tbody>
</table>
<br />
<br />
<br />
<br />
</div>
Thank you to anyone who can answer or comment my post!
I think I might pass the wrong value into the function. But i am not so sure. This is also my first time trying to pass JSON or anything ajax. If you guys want to leave some tips for me down below, it is very much appreciated.
An example of the problem:
The page first loads with a list of items in the default order: [0,1,2,3,4,5]
The user rearranges the order to: [4,5,2,3,1,0]
When the serialized form is posted, it is still the default order: [0,1,2,3,4,5]
I think this is happening because the list items are generated at the page load with a set order, and that order does not change when the UI is updated. Is there a way to submit the updated list of SortOrderOptions?
The list of items:
<div class="row">
<ul id="sortable" style="list-style: none; padding-left: 0px; width: 100%;">
#for (var x = 0; x < Model.SortOrderOptions.Count; x++)
{
<li style="width: 100%;">
<div class="row">
<div class="col-6" style="padding-left:30px;">
<label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" asp-for="#Model.SortOrderOptions[x].SortBy" class="sortBox" /><span></span></label>
<label>#Model.SortOrderOptions[x].Name</label>
<input type="hidden" asp-for="#Model.SortOrderOptions[x].Name" value="#Model.SortOrderOptions[x].Name" />
</div>
<div class="col-3 center">
<label asp-for="#Model.SortOrderOptions[x].Subtotal">
<label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" disabled="#(Model.SortOrderOptions[x].SortBy != true ? "disabled" : null)" asp-for="#Model.SortOrderOptions[x].Subtotal" class="subtotalBox" /><span></span></label>
</label>
</div>
<div class="col-3">
<label asp-for="#Model.SortOrderOptions[x].NewPage">
<label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" disabled="#(Model.SortOrderOptions[x].SortBy != true ? "disabled" : null)" asp-for="#Model.SortOrderOptions[x].NewPage" class="newPageBox" /><span></span></label>
</label>
</div>
</div>
</li>
}
</ul>
</div>
<script src="~/libs/js/jquery.js"></script>
<script src="~/libs/jqueryui/jquery-ui.js"></script>
Javascript:
$("#sortable").sortable({
axis: "y",
containment: "parent"
});
$('#submit').off('click').on('click', function (evt) {
var data = $('form').serialize();
var url = "#Context.Request.Path.Value.Replace("/Test","", StringComparison.OrdinalIgnoreCase)";
evt.preventDefault();
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: dataType,
url: '#Url.Action("PBSCSubmit","Reports")',
beforeSend: function(){
// Show loading spinner while processing
$('#loader').modal({
backdrop: 'static',
keyboard: false
});
},
success: function (data) {
if (data.success) {
//Success with warnings
if (data.warning) {
$('#loader').modal('toggle');
//Toggle the error modal and display messages
$('#errorsModal').modal('toggle');
//Add <br> tags when there is a linebreak in the string. This will add the line breaks into the HTML.
$('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
//Open PDF on warning modal "OK" button click
$('#modalConfirm').on('click', function () {
window.open(url + "/ShowPDF?path=" + data.pdf, "_blank");
});
} else {
//Success without warnings
$('#loader').modal('toggle');
window.open(url + "/ShowPDF?path=" + data.pdf, "_blank");
if (data.csvCreated) {
window.open(url + "/DownloadFile?path=" + data.csv + "&fileName=" + CSVFileName, "_blank");
}
}
} else {
$('#loader').modal('toggle');
//Toggle the error modal and display messages
$('#errorsModal').modal('toggle');
//Add <br> tags when there is a linebreak in the string. This will add the line breaks into the HTML.
$('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
}
},
error: function (jqXHR) {
$('#loader').modal('toggle');
handleAjaxError(jqXHR);
}
});
});
Controller:
public IActionResult PBSCSubmit(PaymentsBySelectionCriteria report)
{
var convertedReport = new PaymentsBySelectionCriteria().ConvertToCriteria(report);
convertedReport.PathToProjectFile = reportPath;
var path = Path.GetDirectoryName(env.WebRootPath) + "\\pdfs\\" + Guid.NewGuid() + ".pdf";
var csvPath = Path.GetDirectoryName(env.WebRootPath) + "\\csvs\\" + Guid.NewGuid() + ".csv";
var reportModel = new ReportPaymentsBySelection();
if (convertedReport.CreateCSVFile == true)
{
convertedReport.CSVFileName = csvPath;
}
reportModel.CreateReportAsPDFOrAddToQueue(convertedReport, path, loggedInUserID, out Notification notification, out bool addedToQueue);
//Add the report to the process queue
if (addedToQueue == true)
{
return Json(new
{
success = false,
message = "The report has been added to the queue."
});
}
if (notification.HasErrors)
{
return Json(new
{
success = false,
message = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)
});
}
return Json(new
{
success = true,
warning = notification.HasWarnings,
message = notification.GetConcatenatedWarningMessage(Environment.NewLine + Environment.NewLine),
pdf = path,
csvCreated = convertedReport.CreateCSVFile,
csv = csvPath
});
}
I came up with my own solution for this by creating a new property to keep track of the index. I created some hidden inputs and added the class sort-index to each of them.
public class SortOrder
{
public string Name { get; set; }
public bool SortBy { get; set; }
public bool Subtotal { get; set; }
public bool NewPage { get; set; }
public int SortIndex { get; set; }
}
When the submit button is clicked, I update the hidden index inputs to re-order to the current position in the UI.
//Update the SortIndex value of each sort order option
$(".sort-index").each(function (i, el) {
//console.log("Index: " + i + ". Value: " + $(this).val());
//Set the value of the sort index input to the index
$(this).val(i);
});
you can do this in one method with Html Table
Create the same thing inside a table
Then allow user to drag and drop the list
finaly get the table rows as a list with the javascript
Above list will be in user arranged way, I will add an example code below
You sort this list as your wish and click the 'ClickMe' button
this code for your reference only,it is different from your code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Easy Drag and Drop HTML Table Rows With jQuery</title>
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="https://getbootstrap.com/docs/4.0/examples/starter-template/starter-template.css" rel="stylesheet">
</head>
<body>
<main role="main" class="container">
<table class="table table-striped table-hover" id="tbl">
<thead class="thead-dark">
<tr>
<th>Row</th>
<th>Name</th>
<th>ID Number</th>
<th>Location</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>01</td>
<td>Rahim Hawkins</td>
<td>1640060874099</td>
<td>Bursa</td>
<td>May 29, 2017</td>
</tr>
<tr>
<td>02</td>
<td>Carter James</td>
<td>1672062705399</td>
<td>Geer</td>
<td>Mar 30, 2019</td>
</tr>
<tr>
<td>03</td>
<td>Merritt Fernandez</td>
<td>1669120981299</td>
<td>Gooik</td>
<td>Jun 3, 2017</td>
</tr>
<tr>
<td>04</td>
<td>Ross Robbins</td>
<td>1640092139299</td>
<td>Lint</td>
<td>Mar 22, 2018</td>
</tr>
<tr>
<td>05</td>
<td>Allistair Warren</td>
<td>1690102625999</td>
<td>Bicester</td>
<td>Dec 22, 2017</td>
</tr>
<tr>
<td>06</td>
<td>Yoshio Finch</td>
<td>1643051322099</td>
<td>Baulers</td>
<td>Sep 15, 2018</td>
</tr>
<tr>
<td>07</td>
<td>Wylie Holland</td>
<td>1662122249099</td>
<td>Penicuik</td>
<td>Apr 22, 2018</td>
</tr>
<tr>
<td>08</td>
<td>Maxwell Lindsay</td>
<td>1637021237499</td>
<td>St. John's</td>
<td>Nov 30, 2018</td>
</tr>
<tr>
<td>09</td>
<td>Orson Schneider</td>
<td>1610061567599</td>
<td>Gresham</td>
<td>Mar 7, 2018</td>
</tr>
<tr>
<td>10</td>
<td>Ahmed Puckett</td>
<td>1626021923499</td>
<td>Valbrevenna</td>
<td>Jul 20, 2018</td>
</tr>
</tbody>
</table>
<button onclick="fun()">ClickMe</button>
</main><!-- /.container -->
<!-- Bootstrap & Core Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script src="https://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$('tbody').sortable();
function fun(){
var table = document.getElementById("tbl");
var noOfrows=table.rows.length;
var res = new Array(noOfrows);
for (var i=0;i<noOfrows;i++){
res[i]=table.rows[i].cells[0].innerHTML;
}
alert(res);
}
</script>
</body>
</html>
I need to parse a remote JSON file using a header with a get request in Angular 5. Not sure how to do it with GET along with header.
Something like this but in Angular 5:
let headers = new Headers({
'key': 'Value',
'key2' :'value2'
});
let request_option = new RequestOptions({ headers: this.headers});
this.http.get("http.//.....", request_option)
.map(res => res.json()
this.user.firstname = user.response.docs[0].FIRST_NAME;
this.user.lastname = user.response.docs[0].LAST_NAME;
JSON:
{
"responseHeader": {
"status":0,
"QTime":1,
},"response":{
"docs":[{
"FIRST_NAME": "John",
"LAST_NAME": "Smith"
}]
}
}
& finally be able to call it in HTML:
<div>{{user.firstname}}</div>
Below is the example for getting json from another server
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
If the response.data is recieved in json string, you can easily parse it using following code
JSON.stringify(response.data)
Below is the working example for getting json from another server and display it in table
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
<script>
(function() {
angular.module("testApp", ['ui.bootstrap']).controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
}]);
}());
</script>
<style></style>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl">
<form name="commonForm">
<table class="table">
<tr>
<th> Name </th>
<th> Gender </th>
<th> Email </th>
<th> Username </th>
<th> Date of Birth </th>
<th> Registered Date </th>
<th> Phone </th>
<th> Mobile </th>
<th> Nationality </th>
<th> Profile </th>
</tr>
<tr ng-repeat="user in userData.results">
<td> {{user.name.first}} {{user.name.last}}</td>
<td> {{user.gender}}</td>
<td> {{user.email}}</td>
<td> {{user.login.username}}</td>
<td> {{user.dob}}</td>
<td> {{user.registered}}</td>
<td> {{user.phone}}</td>
<td> {{user.cell}}</td>
<td> {{user.nat}}</td>
<td>
<img ng-src="user.picture.large">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
In Angular 5 you can use property binding to access properties of DOM elements, in test case:
<div [innerHTML]="post.body"></div>
for reference look here angular.io docs
enter image description hereI am not able Retrieve data from Json file using Angular Js.
Am trying to get the Json data from URL using click function in angular Js and also when click the button add empty tr td in table.
<!doctype html>
<html lang="en" ng-app="sampleapp">
<head>
{% load staticfiles %}
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="{% static 'bootstrap/js/angular.min.js'%}"></script>
<script type="text/javascript" src="{% static 'bootstrap/js/jquery.min.js'%}"></script>
<script src="{% static 'bootstrap/js/bootstrap.min.js'%}" type="text/javascript"></script>
<script type="text/javascript" src="{% static '/bootstrap/js/app_ang.js'%}"></script>
</head>
<body >
<div class="col-sm-12" ng-controller="tablejsonCtrl">
<button class="clickbutton" ng-click="jsonclick();">Show-json</button>
<table rule="all" class="table table-bordered table-hover ">
<tr>
<th>Name</th>
<th>Price</th>
<th>Description</th>
<th>Calories</th>
<th>isbest</th>
</tr>
<tr ng-repeat="value in students.breakfast_menu.food">
<td>{{value.name}}</td>
<td>{{value.price}}</td>
<td>{{value.description}}</td>
<td>{{value.calories}}</td>
<td>{{value.isbest}}</td>
</tr>
</table>
</div>
</body>
</html>
var app =angular.module('sampleapp', [])
app.controller("tablejsonCtrl", function ($scope, $http) {
$scope.jsonclick = function () {
var url = "http://127.0.0.1:8000/static/waste/test.json";
$http.get(url).then(function(response) {
$scope.students = response.data;
});
}
});
Instead of use ".then" try with .success method, so replace this :
$http.get(url).then(function(response) {
$scope.students = response.data;
});
with this :
$http.get('url').success(function (response){
$scope.students= response;
});
You can use HTTP request in local.
Only works for Angular Versions above 1.6
$http.get('./path-to-JSON-file/../someFile.json').
then(function onSuccess(response) {
angular.extend(_this, data);
defer.resolve();
}).
catch(function onError(response) {
console.log(response);
});
for further research: CLICK HERE
I am trying to load in a list of "donors" for my angular application. I get the data from an API, but I doesn't work the way I want it to. I get this error:
$resourceProvider <- $resource <- DonorerCtrl
In my DonorerCtrl class I have the following code:
angular.module("testApp").controller("DonorerCtrl",
function($scope, $http, $resource) {
console.log("Test fra donorerCtrl");
$scope.donorerResource = $resource("http://bloodadmin.cloudapp.net/api/users/:donorid"),
{id: "#donorid"}, { update: {method: "PUT"}};
$scope.donorerVisits = $scope.donorerResource.query();
$http (
{
method: "GET",
url: "http://bloodadmin.cloudapp.net/api/donors"
}).success(function(data) {
$scope.donorerVisits = data;
}).error(function() {
alert("error");
});
$scope.donorerVisits = [];
});
I try to load it in my HTML file with this code:
<div class="form-group col-lg-12">
<table class="table">
<thead>
<tr>
<th>Fornavn</th>
<th>Efternavn</th>
<th>Køn</th>
<th>Fødselsdag</th>
<th>Læs mere</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="visit in donorerVisits">
<td>{{visit.firstname}}</td>
<td>{{visit.lastname}}</td>
<td>{{visit.sex}}</td>
<td>{{visit.age}}</td>
<td><button class="btn btn-default">Læs mere</button></td>
</tr>
</tbody>
</table>
</div>
In my Index html I load in these JS files:
<!-- JS -->
<script src="libs/angular.js" type="text/javascript"></script>
<script src="libs/angular-ui-router.min.js" type="text/javascript"></script>
<script src="libs/angular-resource.js" type="text/javascript"></script>
<!-- Angular Custom -->
<script type="text/javascript">
angular.module("testApp", ['ui.router']);
</script>
<script src="js/controllers/HjemCtrl.js"></script>
<script src="js/controllers/DonorerCtrl.js"></script>
<script src="js/controllers/BlodCtrl.js"></script>
<script src="js/navigation.js"></script>
try:
angular.module("testApp", ['ui.router', 'ngResource']);