I am consuming wcf rest service into angular js application. I am trying to display single record in angular js application based on Account Holder Last Name . when the post the value to wcf service and its receive the values .Its check the values in ado.net code whether the values is valid or invalid . After checking the values ,its able to retrieve Account Holder information in Google chrome network tap response section. But the problem is not displaying anything in webpage .
Here is the Interface .
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetCustomers/{Account_Holder_Last_Name}")]
string GetCustomers(string Account_Holder_Last_Name);
Here is the Implementation .
public string GetCustomers(string Account_Holder_Last_Name)
{
List<object> customers = new List<object>();
string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Holder_Last_Name =#Account_Holder_Last_Name";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Parameters.AddWithValue("#Account_Holder_Last_Name", Account_Holder_Last_Name);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
while (sdr.Read())
{
customers.Add(new
{
Tittle = sdr["Tittle"],
Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
Account_Holder_DOB = sdr["Account_Holder_DOB"],
Account_Holder_House_No = sdr["Account_Holder_House_No"],
Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],
Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
Account_Number = sdr["Account_Number"]
});
}
}
}
conn.Close();
}
return (new JavaScriptSerializer().Serialize(customers));
}
}
Here is the Script code .
#{
Layout = null;
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.IsVisible = false;
$scope.Customers = [];
$scope.Search = function () {
var post = $http({
method: "GET",
url: "http://localhost:52098/HalifaxIISService.svc/GetCustomers/" + encodeURIComponent($scope.Account_Holder_Last_Name),
dataType: 'json',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
});
post.success(function (data, status) {
$scope.Customers = eval(data.d);
$scope.IsVisible = true;
},
function (err) {
console.log("Some Error Occured." + err);
}
);
post.error(function (data, status) {
$window.alert(data.Message);
});
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Account_Holder_Last_Name" />
<input type="button" value="Submit" ng-click="Search()" />
<hr />
<table cellpadding="0" cellspacing="0" ng-show="IsVisible">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th> Tittle</th>
<th>First Name</th>
<th> Last Name</th>
<th> DOB </th>
<th> House No</th>
<th> Street Name</th>
<th>Post Code</th>
<th> Occupation</th>
<th>Account Number</th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td>{{m.Tittle}}</td>
<td>{{m.Account_Holder_First_Name}}</td>
<td>{{m.Account_Holder_Last_Name}}</td>
<td>{{m.Account_Holder_DOB}}</td>
<td>{{m.Account_Holder_House_No}}</td>
<td>{{m.Account_Holder_Street_Name}}</td>
<td>{{m.Account_Holder_Post_Code}}</td>
<td>{{m.Account_Holder_Occupation}}</td>
<td>{{m.Account_Number}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Here is the screen shot wcf service receiving the values .
Here is the screen shot Google chrome network tab able to catch the data and web page does not displaying the data .
Related
This is my model file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ConsumeJson.Models
{
public class ProductModel
{
public List<Product> findAll()
{
List<Product> result = new List<Product>();
result.Add(new Product { Id = "p01", Name = "Product 1", Price = "100", Quantity = "1" });
result.Add(new Product { Id = "p02", Name = "Product 2", Price = "200", Quantity = "2" });
result.Add(new Product { Id = "p03", Name = "Product 3", Price = "300", Quantity = "3" });
return result;
}
public Product find(string id)
{
return findAll().Single(p => p.Id.Equals(id));
}
}
}
This is my HTML file.
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<meta charset="utf-8" />
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script src="Scripts/jquery-3.3.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<title>My Client</title>
</head>
<body ng-controller="productController">
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr ng-repeat="product in result">
<td>{{product.Id}}</td>
<td>{{product.Name}}</td>
</tr>
</table>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
myapp.controller('productController', function ($scope, $http) {
$http(
method: 'GET',
url:'http://localhost:53204/api/product').success(function (response) {
$scope.result = response;
})
})
</script>
</body>
</html>
I want to create product's table with informations but hen i run it as localhost it never display the product's id or name.
It stays like this way. {{Product.Id}} {{Product.Name}} How can i solve this?
You need to change it to using .then()
$http({
method: "GET",
url: "http://localhost:53204/api/product"
}).then(function mySucces(response) {
$scope.result = response.data;
}, function myError(response) {
});
May have many reason.
Check your scope inserted, are you sure that you send ProductId to server side with Http request?.
it's better that use of ngModel instead of dubble braces. check this
and the Important issue is, if your model like this:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
when your API wants to return your response, convert data to Json, attention that your model is KebabCase but your Json in camelCase, but in your html you use of KebabCase.
If all of this issues not work, check your network and check response of your request in response tab, Is there any response or any Ids?
GoodLuck.
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.
Currently I am working on WCF project. I am consuming my wcf project into Angular JS Application but when I run the application it does not provide any error. There are errors when I launch developer tools in Google Chrome and I cannot insert, update and delete etc. It's showing following errors...... Anyone help me to correct this errors I would be grateful.
?o=3&g=EC0825C4-90A4-2692-D257-CD2C2B565912&s=1A2C77E8-0498-4A11-B8B8-D740DBEC71C4&z=1403834305:2 Uncaught SyntaxError: Unexpected token <
2angular.js:12701 OPTIONS http://localhost:50028/StudentService.svc/AddNewStudent 405 (Method Not Allowed)
Index:1 XMLHttpRequest cannot load http://localhost:50028/StudentService.svc/AddNewStudent. Response for preflight has invalid HTTP status code 405
Modules.js:52 Some error Occured[object Object]
Index:1 GET http://localhost:50028/StudentService.svc/GetAllStudent/ 400 (Bad Request)
angular.js:14642 ReferenceError: $log is not defined
at Modules.js:18
at angular.js:17000
at m.$digest (angular.js:18182)
at m.$apply (angular.js:18480)
at l (angular.js:12501)
at XMLHttpRequest.s.onload (angular.js:12655) "Possibly unhandled rejection: {}"
Her is code in Angular JS ...
/// <reference path="../angular.min.js" />
var app;
(function () {
app = angular.module("RESTClientModule", []);
app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService) {
$scope.OperType = 1;
//1 Mean New Entry
GetAllRecords();
//To Get All Records
function GetAllRecords() {
var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
promiseGet.then(function (pl) { $scope.Students = pl.data },
function (errorPl) {
$log.error('Some Error in Getting Records.', errorPl);
});
}
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.StudentID = "";
$scope.Name = "";
$scope.Email = "";
$scope.Class = "";
$scope.EnrollYear = "";
$scope.City = "";
$scope.Country = "";
}
//To Create new record and Edit an existing Record.
$scope.save = function () {
var Student = {
Name: $scope.Name,
Email: $scope.Email,
Class: $scope.Class,
EnrollYear: $scope.EnrollYear,
City: $scope.City,
Country: $scope.Country
};
if ($scope.OperType === 1) {
var promisePost = CRUD_AngularJs_RESTService.post(Student);
promisePost.then(function (pl) {
$scope.StudentID = pl.data.StudentID;
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some error Occured" + err);
});
} else {
//Edit the record
debugger;
Student.StudentID = $scope.StudentID;
var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
promisePut.then(function (pl) {
$scope.Message = "Student Updated Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
};
//To Get Student Detail on the Base of Student ID
$scope.get = function (Student) {
var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.StudentID = res.StudentID;
$scope.Name = res.Name;
$scope.Email = res.Email;
$scope.Class = res.Class;
$scope.EnrollYear = res.EnrollYear;
$scope.City = res.City;
$scope.Country = res.Country;
$scope.OperType = 0;
},
function (errorPl) {
console.log('Some Error in Getting Details', errorPl);
});
}
//To Delete Record
$scope.delete = function (Student) {
var promiseDelete = CRUD_AngularJs_RESTService.delete(Student.StudentID);
promiseDelete.then(function (pl) {
$scope.Message = "Student Deleted Successfuly";
GetAllRecords();
ClearModels();
}, function (err) {
console.log("Some Error Occured." + err);
});
}
});
app.service("CRUD_AngularJs_RESTService", function ($http) {
//Create new record
this.post = function (Student) {
var request = $http({
method: "post",
url: "http://localhost:50028/StudentService.svc/AddNewStudent",
data: Student
});
return request;
}
//Update the Record
this.put = function (StudentID, Student) {
debugger;
var request = $http({
method: "put",
url: "http://localhost:50028/StudentService.svc/UpdateStudent",
data: Student
});
return request;
}
this.getAllStudent = function () {
return $http.get("http://localhost:50028/StudentService.svc/GetAllStudent");
};
//Get Single Records
this.get = function (StudentID) {
return $http.get("http://localhost:50028/StudentService.svc/GetStudentDetails/" + StudentID);
}
//Delete the Record
this.delete = function (StudentID) {
var request = $http({
method: "delete",
url: "http://localhost:50028/StudentService.svc/DeleteStudent/" + StudentID
});
return request;
}
});
})();
Here is the WCF service Code ......
[ServiceContract]
public interface IStudentService
{
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetAllStudent/")]
List<StudentDataContract> GetAllStudent();
[OperationContract]
[WebGet(RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetStudentDetails/{StudentId}")]
StudentDataContract GetStudentDetails(string StudentId);
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/AddNewStudent")]
bool AddNewStudent(StudentDataContract student);
[OperationContract]
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/UpdateStudent")]
void UpdateStudent(StudentDataContract contact);
[OperationContract]
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteStudent/{StudentId}")]
void DeleteStudent(string StudentId);
}
}
Here is Implementation of method of wcf service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCF_REST_Service
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "StudentService" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select StudentService.svc or StudentService.svc.cs at the Solution Explorer and start debugging.
public class StudentService : IStudentService
{
StudentManagementEntities ctx;
public StudentService()
{
ctx = new StudentManagementEntities();
}
public List<StudentDataContract> GetAllStudent()
{
var query = (from a in ctx.Students
select a).Distinct();
List<StudentDataContract> studentList = new List<StudentDataContract>();
query.ToList().ForEach(rec =>
{
studentList.Add(new StudentDataContract
{
StudentID = Convert.ToString(rec.StudentID),
Name = rec.Name,
Email = rec.Email,
EnrollYear = rec.EnrollYear,
Class = rec.Class,
City = rec.City,
Country = rec.Country
});
});
return studentList;
}
public StudentDataContract GetStudentDetails(string StudentId)
{
StudentDataContract student = new StudentDataContract();
try
{
int Emp_ID = Convert.ToInt32(StudentId);
var query = (from a in ctx.Students
where a.StudentID.Equals(Emp_ID)
select a).Distinct().FirstOrDefault();
student.StudentID = Convert.ToString(query.StudentID);
student.Name = query.Name;
student.Email = query.Email;
student.EnrollYear = query.EnrollYear;
student.Class = query.Class;
student.City = query.City;
student.Country = query.Country;
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return student;
}
public bool AddNewStudent(StudentDataContract student)
{
try
{
Student std = ctx.Students.Create();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.Students.Add(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
return true;
}
public void UpdateStudent(StudentDataContract student)
{
try
{
int Stud_Id = Convert.ToInt32(student.StudentID);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
std.Name = student.Name;
std.Email = student.Email;
std.Class = student.Class;
std.EnrollYear = student.EnrollYear;
std.City = student.City;
std.Country = student.Country;
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
public void DeleteStudent(string StudentId)
{
try
{
int Stud_Id = Convert.ToInt32(StudentId);
Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
ctx.Students.Remove(std);
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new FaultException<string>
(ex.Message);
}
}
}
}
Here is HTML CODE ...
#{
Layout = null;
}
<!DOCTYPE html>
<html data-ng-app="RESTClientModule">
<head title="ASAS">
<title></title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/MyScripts/Modules.js"></script>
</head>
<body>
<table id="tblContainer" data-ng-controller="CRUD_AngularJs_RESTController">
<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>Name</th>
<th>Email</th>
<th>Class</th>
<th>Year</th>
<th>City</th>
<th>Country</th>
<th></th>
<th></th>
</tr>
<tbody data-ng-repeat="stud in Students">
<tr>
<td></td>
<td><span>{{stud.StudentID}}</span></td>
<td><span>{{stud.Name}}</span></td>
<td><span>{{stud.Email}}</span></td>
<td><span>{{stud.Class}}</span></td>
<td><span>{{stud.EnrollYear}}</span></td>
<td><span>{{stud.City}}</span></td>
<td><span>{{stud.Country}}</span></td>
<td>
<input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" />
</td>
<td>
<input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" />
</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>Student ID</span>
</td>
<td>
<input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Student Name</span>
</td>
<td>
<input type="text" id="sName" required data-ng-model="Name" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Email</span>
</td>
<td>
<input type="text" id="sEmail" required data-ng-model="Email" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Class</span>
</td>
<td>
<input type="text" id="sClass" required data-ng-model="Class" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Enrollement Year</span>
</td>
<td>
<input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>City</span>
</td>
<td>
<input type="text" id="sCity" required data-ng-model="City" />
</td>
</tr>
<tr>
<td></td>
<td>
<span>Country</span>
</td>
<td>
<input type="text" id="sCountry" required data-ng-model="Country" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<input type="button" id="save" value="Save" data-ng-click="save()" />
<input type="button" id="Clear" value="Clear" data-ng-click="clear()" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
Here is screen shot when I run the application..
First, you need to use * in [ServiceContract]. like this:
[WebInvoke(Method = "*"
That way, you allow your method to receive OPTIONS requests.
Then you should add this to your web.config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type, Accept" />
</customHeaders>
</httpProtocol>
Do not forgot to handle OPTIONS requests. Something like this will solve it:
public List<StudentDataContract> GetAllStudent()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
return null;
var query = (from a in ctx.Students
select a).Distinct();
List<StudentDataContract> studentList = new List<StudentDataContract>();
query.ToList().ForEach(rec =>
{
studentList.Add(new StudentDataContract
{
StudentID = Convert.ToString(rec.StudentID),
Name = rec.Name,
Email = rec.Email,
EnrollYear = rec.EnrollYear,
Class = rec.Class,
City = rec.City,
Country = rec.Country
});
});
return studentList;
}
That's it. Good luck.
I'm using AngularJs in Asp.net Mvc5 for create single page application.
I have a problem , when i use ng-repeat for show data in table , my data doesn't show in table but show empty rows
This is my Home Controller
angularFormsApp.controller("HomeController",
function ($scope, $location, DataService) {
DataService.getEmployees().then(
function (results) {
$scope.names = results.data;
console.log(results.data);
console.log("This is console");
},
function (error) {
// on error
alert("error read data" + error);
}
);
});
This is my DataService
angularFormsApp.factory('DataService',
function ($http) {
var getEmployees = function () {
return $http.get("Employee/GetEmployees");
};
return {
getEmployees: getEmployees
};
});
This is My Html Page
<div ng-app="angularFormsApp">
<div ng-controller="HomeController">
{{ Namef }}
<table class="table table-hover ">
<thead>
<tr>
<th>Name Employee</th>
<th>Note</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in names">
<td>{{ item.FullName }}</td>
<td>{{ item.Note }}</td>
<td>
Edite
Delete
</td>
</tr>
</tbody>
</table>
</div>
</div>
This is My EmployeeController
public class EmployeeController : Controller
{
// GET: Employee
DataLayer.WebapplicationContext db = new DataLayer.WebapplicationContext();
public ActionResult GetEmployees()
{
var data = db.Employees.ToList();
var camelCaseFormatter = new JsonSerializerSettings();
camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
var jsonResult = new ContentResult
{
Content = JsonConvert.SerializeObject(data, camelCaseFormatter),
ContentType = "application/json"
};
return jsonResult;
//return new HttpStatusCodeResult(404, "Our custom error message...");
}
When i run this project i saw empty rows , it's above picture show my problem.
Picture
And this is console log enter image description here
I'm try this code and solve it my problem.In EmployeeController change ActionResult to JsonResult
public JsonResult GetEmployees()
{
using (WebapplicationContext Obj = new WebapplicationContext())
{
List<Employee> Emp = Obj.Employees.ToList();
return Json(Emp, JsonRequestBehavior.AllowGet);
}
}
I want to populate the data into the datatable but no data is getting populated into the table.
Error I'm getting on debugging is:
Uncaught TypeError: Cannot read property 'getContext' of null
html:
<table class="display table table-bordered table-striped" id="example">
<thead>
<tr>
<th>User Name</th>
<th>Email Id</th>
<th>Group Name</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.user}}</td>
<td>{{item.email}}</td>
<td>{{item.groupName}}</td>
<td>{{item.createdAt}}</td>
</tr>
</tbody>
</table>
controller:
(function () {
"use strict";
angular.module('app').controller('superAdminController', function ($scope, AuthenticationService, $timeout, $location, $http, myConfig) {
AuthenticationService.loadSuperAdmin(function (response) {
if (response.data.success) {
$scope.populateTable(response.data);
console.log(response.data);
} else {
$scope.items = [];
}
});
$scope.populateTable = function (data) {
$scope.items = data.loadSuperAdminData;
$timeout(function () {
$("#example").dataTable();
}, 200)
};
});
}());
In controller, you can populate your server response like this.
$.post(MY_CONSTANT.url + '/api_name',{
access_token: accessToken
}).then(
function(data) {
var dataArray = [];
data = JSON.parse(data);
var lst = data.list;
lst.forEach(function (column){
var d = {user: "", email: "", group: "", created: ""};
d.user = column.user;
d.email = column.email;
d.groupName = column.group;
d.createdAt = column.created;
dataArray.push(d);
});
$scope.$apply(function () {
$scope.list = dataArray;
// Define global instance we'll use to destroy later
var dtInstance;
$timeout(function () {
if (!$.fn.dataTable) return;
dtInstance = $('#datatable4').dataTable({
'paging': true, // Table pagination
'ordering': true, // Column ordering
'info': true, // Bottom left status text
// Text translation options
// Note the required keywords between underscores (e.g _MENU_)
oLanguage: {
sSearch: 'Search all columns:',
sLengthMenu: '_MENU_ records per page',
info: 'Showing page _PAGE_ of _PAGES_',
zeroRecords: 'Nothing found - sorry',
infoEmpty: 'No records available',
infoFiltered: '(filtered from _MAX_ total records)'
}
});
var inputSearchClass = 'datatable_input_col_search';
var columnInputs = $('tfoot .' + inputSearchClass);
// On input keyup trigger filtering
columnInputs
.keyup(function () {
dtInstance.fnFilter(this.value, columnInputs.index(this));
});
});
// When scope is destroyed we unload all DT instances
// Also ColVis requires special attention since it attaches
// elements to body and will not be removed after unload DT
$scope.$on('$destroy', function () {
dtInstance.fnDestroy();
$('[class*=ColVis]').remove();
});
});
});