How to get JSON with Angular JS - javascript

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;

Related

Displaying JSON content in table rows using angularjs and codeigniter

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

$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.

AngularJS - Duplicate Key in ngrepeat error

I want to parse this controller in my view:
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 I have implemented the parsing like that:
<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">
<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>
What I am currently getting is:
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.2.8/ngRepeat/dupes?p0=p%20in%20product&p1=string%3A%22
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)
I tried to change it to:
p in product by $id
which gives me a syntax error.
I appreciate your suggestions!
try this
<tr ng-repeat="p in product track by $index">
<td>{{p.id}}</td>
<td>{{p.title}}</td>
<td>{{p.price}}</td>
<td>{{p.description}}</td>
</tr>
Usage of track by

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">

ajax call not sending data correctly

There is something wrong with the way I am using the ajax call.
When I place the ajax call inside the block, it executes the error function in the ajax callback. When the ajax call is moved outside the block, the variable subcate passed to server is undefined.
var that = this;
var subCate ='' ;
var tr = $('#tbl').find('tr');
//My block
tr.bind('click', function(event) {
var values = '';
tr.removeClass('highlight');
var tds = $(this).addClass('highlight').find('td');
subCate = tds.find('#myid').text();
alert(subCate);
//Tried moving it out of the block but not much of help
$.ajax({
url: '/playground',
type: 'POST',
data: { id: subCate},
success: function(data){
alert("Sub category recvd");
console.log("successs");
},
error: function(jqXHR){
console.log("failed");
alert("failed");
}
});
});
//Ajax call moved here
Here is the node.js server code :
app.post('/playground', function(req, res) {
debug("Inside post(/playground) ",req.body.id);
res.send('ok', 200);
});
Hi Here is the snippet of HTML table, that will give an idea what the jquery code is doing
<div id="category-container">
<div id="category-form">
<h1></h1>
<p id="sub1" class="subheading">Select a category</p>
<!--hr-->
<div style="margin:20px" class="container">
<table id="tbl" class="table table-bordered table-striped">
<thead>
<tr>
<!--th(style='width:40px') #-->
<th style="width:180px">Name</th>
<th style="width:200px">Location</th>
<th style="width:180px">Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div id="myid"><a id="item" href="/playground/:0">Electronics</a></div>
</td>
</tr>
<tr>
<td>
<div id="myid"><a id="item" href="/playground/:1">Real Estate</a></div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Thanks in advance guys !
Add event.preventDefault() at the top of your bind.
Also, I recommend changing the event binding to the following:
$('#tbl').on('click', 'tr', function(event) {
event.preventDefault();
// your code
});

Categories

Resources