Displaying JSON content in table rows using angularjs and codeigniter - javascript

I'm just trying to fetch contents from server and display it in a table using Angularjs. I'm been trying this from a while, but did not got any solution yet. Btw, I'm working on CodeIgniter framework.
Here is my CodeIgniter controller;
public function list_agents() {
if($this->is_logged_in ()) {
$agents = $this->generic_model->general_fetch('agent_master');
echo json_encode($agents);
}
else {
redirect(base_url());
}
}
In the above code, instead of echo I used print, print_r also.. But still its not working.
Here is my js file function;
(function () {
var addApp = angular.module('agentApp', ['ngRoute']);
addApp.controller('agentAddController', function ($scope, $http, growl) {
$scope.receivedData = [];
$http({
method : 'POST',
url : 'agent/list_agents',
headers : {
"Content-Type" : "application/json"
}
}).then(function (data) {
$scope.receivedData = JSON.parse(data);
});
});
})();
And in this above code I used with and without JSON.parse function. Didn't got the correct result.
Here is my view;
<section class="content" ng-app="agentApp" ng-controller="agentAddController">
<div class="row">
<div class="col-md-12">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Manage Agents</h3>
</div>
<div class="box-body">
<table class="table table-striped table-bordered" id="agents_table">
<thead>
<tr>
<th>Sl No.</th>
<th>Agent Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<div ng-repeat="data in receivedData">
<tr>
<td>{{ $index + 1 }}</td>
<td>{{ data.agent_name }}</td>
<td><button class="btn btn-warning btn-xs"><i class="fa fa-trash" aria-hidden="true"></i></button></td>
</tr>
</div>
</tbody>
<tfoot>
<tr>
<th>Sl No.</th>
<th>Agent Name</th>
<th>Actions</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</section>
I know if I put ng-repeat inside tr tag I'll get the perfect result, but I don't want to do that because, I'm working with adminLTE. So there is a function DataTable() in adminLTE where it'll apply search and pagination to the table. If I give ng-repeat to tr, these functionalities can not be added.

Try: $scope.receivedData = JSON.parse(data.data);
The response object is not only the data itself, that's why the 5 rows. It gives back, data, headers, status, etc...
https://docs.angularjs.org/api/ng/service/$http

Related

Angular JS Display Response Values

I'm trying to display data from one page to another in Angular JS. Using displayResponse in Firefoxes Console, the Response data seems to be retrieved however I'm having trouble trying to display the values on the page which is troublesome since a Team member was able to get them to display properly on other pages on the site.
Here is the Code so far (I have removed chucks of the script to save screen space. These bits of code are not relevant to the issue afaik):
var app = angular.module("myApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/ViewSalesRecords', {
templateUrl: 'view-sales-records.html',
controller: 'salesRecordController'
}).
when('/ViewSingleSale', {
templateUrl: 'view-single-sale.html',
controller: 'salesRecordController'
});
});
app.controller('salesRecordController', ['$scope', '$http', function($scope, $http) {
$scope.displaySingleSale = function(sale_id) {
$http.post('read_sale.php', {
'sale_id': sale_id
})
.then(function(response) {
$scope.singleSalesRecord = response.data;
console.log($scope.singleSalesRecord);
})
}
$http.get("read_sale.php")
.then(
function(response) {
$scope.salesRecords = response.data;
}
)
}]);
<head>
<link href="./styles/style.css" rel="stylesheet">
</head>
<table class="table table-hover" data-ng-model="sale_id">
<p><strong>Sale ID: {{displayResponse}} </strong> </p>
<p><strong>Sale Date: </strong> </p>
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Item Total</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="s in singleSalesRecord">
<td>{{s.product_id}}</td>
<td>{{s.product_name}}</td>
<td>{{s.quantity}}</td>
<td>${{s.product_price}}</td>
</tr>
</tbody>
</table>
<p><strong>Total: ${{s.orderTotal}}</strong></p>
The page that is sending the data
<head>
<link href="./styles/style.css" rel="stylesheet">
</head>
<div>
<input class="form-control searchBar" data-ng-model="searchText.sale_id" type="text" placeholder="Search sales by Sale ID">
<table class="table table-hover">
<thead>
<tr>
<th>Sale ID</th>
<th>Total items</th>
<th>Total price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="s in salesRecords | filter:searchText:strict">
<td>{{s.sale_id}}</td>
<td>{{s.TotalItems}}</td>
<td>${{s.orderTotal}}</td>
<td>
<button class="btn btn-primary">View</button>
<button class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
So wall of text taken into consideration, what am I doing wrong? I will admit I'm not too familiar with AngularJS so this might be a very amateur mistake on my part.
I figured out that the problem was that the values that I wanted to transfer were been wiped when I moved to another page. So I decided to simply display them on the first page instead hyperlinking to another.

AngularJS: new object not showing in table

I am using dir-paginate library to paginate my data on the page. The issue I am having is when I am adding a new object to the list and viewing this on the page instantly. On the controller side every thing seems to work just alright.
Here is my controller
/**
* Array of all the items
*/
$scope.allItems = [];
$scope.postResource = function() {
ProjectsFactory.save($scope.newProject)
.success(function(data) {
$scope.allItems.push(data);
console.log($scope.allItems);
$scope.newProject = ''
ToastService.show('Added successfully!');
})
.error(function(data) {
sweetAlert("Oops...", "Something went wrong!", "error");
console.log(data);
});
}
Notice the log I am doing right there. On the console page I can see the new object is being added to the rest of the objects. I believe the issue is occurring on the view side which looks just like this.
<table class="table table-bordered table-hover table-condensed bg-white" st-table="rowCollectionBasic">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="item in allItems | filter: search.query | itemsPerPage : itemPerPage" total-items="totalProjects" current-page="currentPage">
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td style="width:150px">
<button class="btn btn-info btn-sm" ng-click="showEditDialog($event, item)">
<i class="glyphicon glyphicon-edit"></i>
</button>
<button class="btn btn-danger btn-sm" ng-click="deleteResource(item, $index)">
<i class="glyphicon glyphicon-trash"></i>
</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="20" class="text-center">
<dir-pagination-controls on-page-change="pageChanged(newPageNumber)" boundary-links="true"></dir-pagination-controls>
<md-progress-circular md-mode="indeterminate" ng-if="AjaxInProgress"></md-progress-circular>
</td>
</tr>
</tfoot>
To see the new created object on the page, I need to either refresh the page or click somewhere else and return to the same page again.
Someone has an idea what I am doing wrong?
Update #1
The project service has $http
// save a new resource
save: function(data) {
return $http({
url: $rootScope.baseUrl + 'projects',
method: 'POST',
data: data
});
},
Thanks!

$scope array not holding value for ng-repeat

I am trying to use an ng-repeat on data that is fetched from an api (returned as JSON) When I do a console.log($scope.wines) before the end of the function it holds the value but then at the end of the function $scope.wines is empty again. I feel that this is causing my ng-repeat="wine in wines" isn't showing up correctly.
Here is my JS:
app.controller("MainController", function($scope){
var api_key = "22x";
$scope.wines = [];
// Search Wine Function
$scope.SearchWine = function(){
$scope.wines = [];
var search_api_url = "http://services.wine.com/api/beta2/service.svc/json/catalog?search=" + $scope.wine + "&size=200&apikey=" + api_key;
var i = 1;
$("#wine_list").html("");
$(".loading").show();
$(".alert").hide();
$("input[type='text']").val("").focus();
$.getJSON(search_api_url, function(data) {
$.each(data, function(key, value) {
if(key == "Products") {
$.each(value.List, function(k, v) {
$scope.wines.push(v);
});
console.log($scope.wines);
$(".loading").hide();
}
});
console.log($scope.wines);
});
console.log($scope.wines);
}; //End SearchWine
});
and here is my HTML
<div ng-controller="MainController">
<header>
<a href="http://powersearch.bestwine.com" class="brand">
<img src="assets/images/logo.png" alt="">
</a>
<div class="col-md-6 col-md-offset-3">
<form class="search_form">
<div class="input-group">
<input type="text" class="form-control" ng-model="wine" placeholder="Search by Winery or AVA...">
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" ng-click="SearchWine()">Search</button>
</span>
</div><!-- /input-group -->
<p class="help-block">You can also search international! Try typing in 'Burgundy'</p>
</form>
</div>
</header>
<div class="container">
<div class="col-md-12">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class='text-center'>#</th>
<th>Wine Name</th>
<th>Wine Appellation</th>
<th>Wine Price</th>
<th>Favorite</th>
</tr>
</thead>
<tbody id="wine_list">
<tr ng-repeat="wine in wines">
<td>{{ wine.Name }}</td>
<td>{{ wine.Appellation.Name }}</td>
</tr>
</tbody>
</table>
<div class="alert alert-info">Type in above to start.</div>
</div>
</div>
</div>
And here is what console displays when running:
If you need anything else, let me know!
Use $resource or $http to fetch data instead of jQuery $.getJson
Here you have detailed answer: AngularJS: factory $http.get JSON file
Additionally avoid using jQuery like this in your Angular code:
$("#wine_list").html("");
$(".loading").show();
$(".alert").hide();
$("input[type='text']").val("").focus();
...
Tasks like this can be handled by angular directives ng-show, ng-hide etc.

How to get JSON with Angular JS

I am trying to get my table filled with data. The url gives json back, but I don't know how to call json in angular.
This my my services.js:
angular.module('OrganisatieApp.services', [])
.factory('organisatieAPIservice', function($resource) {
var organisatieAPIservice = [];
organisatieAPIservice.getOrganisaties = function(){
return $http({
method: 'JSON_CALLBACK',
url: 'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties'
});
}
return organisatieAPIservice;
})
controller.js :
angular.module('OrganisatieApp.controllers', []).
controller('organisatieController',function($scope, organisatieAPIservice) {
$scope.organisatieList = [];
organisatieAPIservice.getOrganisaties().success(function (response) {
//Assign response in Callback
$scope.organisatieList = response();
});
});
app.js:
angular.module('OrganisatieApp', [
'OrganisatieApp.controllers',
'OrganisatieApp.services' ]);
My html div :
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Organisatie naam</th>
<th>Organisatie plaats</th>
<th>Organisatie Curriculum</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="organisatie in organisatieList">
<td>{{$index + 1}}</td>
<td>
<img src="/img/logos/{{organisatie.Organisatie.logo}}.png" />
{{organisatie.Organisatie.orgNaam}} {{organisatie.Organisatie.orgVolledig}}
</td>
<td>{{organisatie.Constructors[0].provincie}}</td>
<td>{{organisatie.curriculum}}</td>
</tr>
</tbody>
</table>
<ng-view></ng-view>
</div>
</div>
</div>
<div class="col-md-6">
<div class="page-header">
<h1>Opleidingsprofiel</h1>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<ul class="nav nav-pills" role="tablist">
<li role="presentation">Aantal Organisaties<span class="badge">3</span></li>
</ul>
</h3>
</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Organisatie naam</th>
<th>Organisatie plaats</th>
<th>Organisatie Curriculum</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="organisatie in organisatieList">
<td>{{$index + 1}}</td>
<td>
<img src="/img/logos/{{organisatie.Organisatie.logo}}.png" />
{{organisatie.Organisatie.orgNaam}} {{organisatie.Organisatie.orgVolledig}}
</td>
<td>{{organisatie.Constructors[0].provincie}}</td>
<td>{{organisatie.curriculum}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
What am I doing wrong? I know that i am trying to call jsonp but how do I call for json.
Seems like there are couple of problem with your code.
Your jsonp call url must have callback parameter with value JSON_CALLBACK like callback=JSON_CALLBACK & its should be of type jsonp.
Code
return $http.jsonp({'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties?callback=JSON_CALLBACK'});
OR
return $http({
method: 'jsonp',
url: 'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties?callback=JSON_CALLBACK'
});
You should do change $scope.organisatieList = response(); to $scope.organisatieList = response; because the response contains a data.
organisatieAPIservice.getOrganisaties().success(function (response) {
//Assign response in Callback
$scope.organisatieList = response;
});
In this line, just add the "$http" as a dependency of your service, like this:
angular.module('OrganisatieApp.services', [])
.factory('organisatieAPIservice', function($resource,$http) {
//your code here
You need to add this to be able to send the request, otherwise for angular the $http variable is not defined (or imported as a dependency). And yes, like #pankajparkar and #vishnu say, you need to change in your controller this line:
$scope.organisatieList = response();
For this one:
$scope.organisatieList = response;

No data over json

I am using angularjs 1.2.8 with grails 2.3.4 backend. I am providing a Restful Api over the grails Resources tag.
I have a view were I load the data:
<div class="container main-frame" ng-app="testapp"
ng-controller="searchController" ng-init="init()">
<h1 class="page-header">Products</h1>
<table class="table">
<thead>
<tr>
<th width="25px">ID</th>
<th>TITLE</th>
<th>PRICE</th>
<th>Description</th>
<th width="50px"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="p in product by $id">
<td>{{p.id}}</td>
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td>{{p.description}}</td>
<!-- ng-show="user.id &&user.id==e.user_id" -->
</tr>
</tbody>
</table>
<!-- ng-show="user.username" -->
<p>
</div>
I am using the searchController to load the data:
testapp.controller("searchController", function($scope, $rootScope, $http, $location) {
var load = function() {
console.log('call load()...');
var url = 'products.json';
if ($rootScope && $rootScope.appUrl) {
url = $rootScope.appUrl + '/' + url;
}
$http.get(url)
.success(function(data, status, headers, config) {
$scope.product = data;
angular.copy($scope.product, $scope.copy);
});
}
load();
});
However in my postgresql db there is data available, but I only get:
and no expection at all:
Any suggestions what I can do to check that?
PS.: Controller is loaded!
UPDATE
Using
<tr ng-repeat="p in product track by p.id">
I am getting an error:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.8/ngRepeat/dupes?p0=p%20in%20product%20track%20by%20p.id&p1=undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:6:449
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:184:445
at Object.fn (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:99:371)
at h.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:100:299)
at h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:103:100)
at f (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:67:98)
at E (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:71:85)
at XMLHttpRequest.v.onreadystatechange (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js:72:133) angular.js:9413
UPDATE2
The json representation looks like that:
[{"class":"com.testapp.Product.BasicProduct","id":1,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":5.0,"title":"Product1"},{"class":"com.testapp.Product.BasicProduct","id":2,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":75.0,"title":"Product2"},{"class":"com.testapp.Product.BasicProduct","id":3,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":50.0,"title":"Product3"},{"class":"com.testapp.Product.BasicProduct","id":4,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":25.0,"title":"Product4"},{"class":"com.testapp.Product.BasicProduct","id":5,"dateCreated":"2014-02-17T13:43:13Z","description":"blblblblbalablablalbalbablablablablblabalalbllba","lastUpdated":"2014-02-17T13:43:13Z","price":15.0,"title":"Product5"}]
Fix the ngRepeat syntax:
<tr ng-repeat="p in product track by p.id">

Categories

Resources