Issues accessing json data using AngularJS - angularjs

I've just started learning angularJS and am trying to figure out why the following code doesn't work
<html>
<head>
<title>Angular JS Ajax</title>
</head>
<body>
<div ng-app="mainApp" ng-controller="studentController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat="student in students">
<td>{{ student.Name }}</td>
<td>{{student.RollNo}}</td>
<td>{{student.Percentage}}</td>
</tr>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp");
mainApp.controller("studentController", function($scope,$http){
var url = "data.txt";
$http.get(url).success(function(response){
$scope.students = response;
});
});
</script>
</body>
</html>
When I change the attribute of ng-app to "" (instead of "mainApp"'), and replace the` code above with the following, the application works.
I'd really appreciate if anyone could explain to me why this is the case.
<script>
function studentController($scope, $http){
var url = "data.txt";
$http.get(url).success(function(response){
$scope.students = response;
});
};
</script>
Here's the data.txt file:
[
{
"Name": "Mahesh Parashar",
"RollNo": 101,
"Percentage": "80%"
},
{
"Name": "Dinkar Kad",
"RollNo": 191,
"Percentage": "75%"
}
]
Thank you!

You forgot to add [] with app module declaration
var mainApp = angular.module("mainApp",[]);

The first one is not working because you don't supply the right syntax for mainApp. You need to add [] for module declaration.
This should look like below:
var mainApp = angular.module('mainApp', []);
mainApp.controller('studentController', function($scope, $timeout) {
var url = "data.txt";
$http.get(url).success(function(response) {
$scope.students = response;
});
});
The second one is working fine simply because you don't have any app module declaration.

You need to Parse it to json object
Please try JSON.parse.
jsonObj = JSON.parse(response);
Hope this will help you

Related

Can't retrieve data from controller AngularJS

I am learning AngularJS (so I'm a noob to this) I'm following a tutorial on Udemy. I even looked at the docs and have tried the wiring they have presented. I just can't seem to get the customers data in the table. What am I doing wrong and an explanation would be appreciated so I can learn the right way of AngularJS for the interview? Any help is much appreciated. By the way I'm using the latest version of AngularJS 1.7
(function () {
var CustomersController = function($scope) {
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [{name:'sanjeet', joined:'2000-12-02', orderTotal: 10.096, age: 26}, {name:'gurpreet', orderTotal:201.961, joined:'2005-12-07',age: 24}, {name:'nikki', orderTotal: 14.561, joined:'2001-11-02', age: 25}];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !scope.reverse;
};
};
angular.module('app').contoller('CustomersController', CustomersController)
}())
// app.controller('CustomersController', ['$scope', function($scope) {
// $scope.sortBy = 'name';
// $scope.reverse = false;
//
// $scope.customers = [{name:'sanjeet', joined:'2000-12-02', orderTotal: 10.096, age: 26}, {name:'gurpreet', orderTotal:201.961, joined:'2005-12-07',age: 24}, {name:'nikki', orderTotal: 14.561, joined:'2001-11-02', age: 25}];
//
// $scope.doSort = function(propName) {
// $scope.sortBy = propName;
// $scope.reverse = !scope.reverse;
// };
// }])
<!DOCTYPE html>
<html ng-app>
<head>
<title>My first AngularJS project</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h3>Customers</h3>
Filter: <input type="text" ng-model="customerFilter.name"/>
<br />
<table ng-controller="CustomersController">
<tr>
<th ng-click="doSort('name')">
Name
</th>
<th ng-click="doSort('age')">
Age
</th>
<th ng-click="doSort('joined')">
Joined
</th>
<th ng-click="doSort('orderTotal')">
Order Total
</th>
</tr>
<tr ng-repeat="customer in customers | filter: customerFilter | orderBy:sortBy:reverse" >
<td>
{{customer.name}}
</td>
<td>
{{customer.age}}
</td>
<td>
{{customer.joined | date: 'yyyy-MM-dd'}} <!--medium, longDate -->
</td>
<td>
{{customer.orderTotal | currency: 'y'}}
</td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src="app/controllers/customersController.js"></script>
<script> var app = angular.module('app', [])</script>
</body>
</html>
You have multiple issues causing your app to not load. You should consider using angular.js rather than angular.min.js to receive better error messages in the console, which would help you to identify your errors.
You have a typo in your controller code. angular.module('app').contoller('CustomersController', CustomersController). .controller is missing an r.
You cannot use <html ng-app> in newer releases of angular (1.3+). This is a very old syntax. The correct syntax is to identify the app module. <html ng-app="app">.
Your App module must be defined before the controllers that use it. i.e.
<script> var app = angular.module('app', [])</script>
has to come before
<script src="app/controllers/customersController.js"></script>
Your Filter: <input type="text" ng-model="customerFilter.name"/> line is outside the controller, and thus won't function. You should move the ng-controller="CustomersController" to the body instead of the table, or a wrapping div.
I created a plunker and updated your code, showing the app in a functional status.

Displaying data using AngularJS

I am trying to represent some data taken from database in a table. I am using jersey as back-end and I have tested it in Postman that it works. The problem is I cannot display my data in the table in front-end, when I use AngularJS. It only shows me a blank table, without data at all. I am pretty new to AngularJS and I really want anyone of you to help me find the problem with my piece of code below.
list_main.js
angular.module('app', [])
.controller('ctrl', function($scope, $http){
$scope.bookList = [];
$scope.loadData = function(){
$http.get('http://localhost:8080/BookCommerce/webapi/list').then(function(data){
$scope.bookList = data;
console.log($scope.bookList);
})
}
$scope.loadData();
})
index2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Of Books</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></s‌​cript>
<script src="js/list_main.js"></script>
</head>
<body>
<div class="row" data-ng-controller="ctrl" data-ng-app="app" data-ng-init="loadData()" style="margin: 10px;">
<div class="col-md-7">
<div class="panel panel-primary">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="exampleone">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in bookList">
<td>{{book.book_id}}</td>
<td>{{book.book_title}}</td>
<td>{{book.book_author}}</td>
<td>{{book.book_description}}</td>
<td>{{book.book_price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
ListDAO.java
public class ListDAO {
public List<Book> findAll() {
List<Book> list = new ArrayList<Book>();
Connection c = null;
String sql = "SELECT * FROM book";
try {
c = ConnectionHelper.getConnection();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionHelper.close(c);
}
return list;
}
protected Book processRow(ResultSet rs) throws SQLException {
Book book = new Book();
book.setBook_id(rs.getInt("book_id"));
book.setBook_title(rs.getString("book_title"));
book.setBook_author(rs.getString("book_author"));
book.setBook_description(rs.getString("book_description"));
book.setBook_price(rs.getInt("book_price"));
return book;
}
}
ListResource.java
#Path("/list")
public class ListResource {
ListDAO dao=new ListDAO();
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Book> findAll() {
System.out.println("findAll");
return dao.findAll();
}
}
Please help me. Thank you!
Okay this is much better than the last time,
There's still some bits wrong with your JS - it should look like this :
// Code goes here
var baseUrl = "https://demo5019544.mockable.io/";
angular.module('app', [])
.controller('ctrl', function($scope, $http){
$scope.bookList = [];
$scope.loadData = function(){
$http.get(baseUrl + 'BookCommerce/webapi/list').then(function(data){
$scope.bookList = data.data;
})
}
})
I made a demo REST service at : https://demo5019544.mockable.io/BookCommerce/webapi/list
which produces the kind of output your web service should product, I tested the code with this web service and with the tweaks I made it worked -- Yay.
The last thing I'd do now is check that your web service is throwing out the same / similar output that my mock is producing.

Angular JSON Response

Below is a json response from my API. I would like to utilize ng-repeat in my html in order to show this data back to an end-user. How do I go about in my controller de-serializing this json data.
{
"message": "Query to return servers",
"result": [
{
"meta": [
"Computer",
"SQLPort",
"Domain"
],
"rows": [
[
"MyCompterName",
"1433",
"XXXX"
]
]
}
]
}
here is the code for the app.js that get loaded into the index.html
var app = angular.module('DSCApp', ['ngRoute', 'ngResource','ui.router']);
Config
app.config(function($routeProvider){
$routeProvider
.when('/DSC', {
templateUrl: "DSC.html",
controller: 'DscController'
})
.otherwise({ redirectTo: '/' });
});
Data Factory
app.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api';
var dataFactory = {};
dataFactory.getServers = function () {
return $http.get(urlBase);
};
return dataFactory;
}]);
Controller
app.controller('DscController', ['$scope', 'dataFactory',
function ($scope, dataFactory) {
$scope.status
$scope.servers;
getServers();
function getServers() {
dataFactory.getServers()
.success(function (srv) {
$scope.servers = srv;
})
.error(function (error) {
$scope.status = 'Unable to load server data: ' + error.message;
});
}
}]);
Using ng-repeat in both the table head and table body should work.
<html ng-app='app' ng-controller='DscController'>
<head>
</head>
<body>
<div class="container">
<div class="jumbotron">
<table ng-if="servers" class="table table-bordered">
<thead>
<tr>
<th ng-repeat="head in servers.result[0].meta">{{head}}</th>
</tr>
</thead>
<tbody ng-repeat="r in servers.result">
<tr ng-repeat="row in r.rows">
<td ng-repeat="item in row">{{item}}</td>
</tr>
</tbody>
</table>
<p ng-if="!servers">{{status}}</p>
</div>
</div>
</body>
</html>
I've included the necessary repeats to handle the data exactly as it was presented. I assume the meta will be the same for all results.

AngularJS ng-click not firing controller method

I'm sure everyone has seen questions of a similar ilk, and trust me when I say I have read all of them in trying to find an answer. But alas without success. So here goes.
With the below code, why can I not get an alert?
I have an ASP.Net MVC4 Web API application with AngularJS thrown in. I have pared down the code as much as I can.
I know that my AngularJS setup is working correctly because on loading my view it correctly gets (via a Web API call) and displays data from the database into a table (the GetAllRisks function). Given that the Edit button is within the controller, I shouldn't have any scope issues.
NB: the dir-paginate directive and controls are taken from Michael Bromley's excellent post here.
I would appreciate any thoughts as my day has degenerated into banging my head against my desk.
Thanks,
Ash
module.js
var app = angular.module("OpenBoxExtraModule", ["angularUtils.directives.dirPagination"]);
service.js
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}});
controller.js
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
$log.error("Some error in getting risks.", errorPl);
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
Index.cshtml
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="OpenBoxExtraModule">
<head>
<title>Risks</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="~/Scripts/angular.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/Pagination/dirPagination.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/module.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/service.js"></script>
<script type="text/javascript" src="~/Scripts/AngularJS/controller.js"></script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr dir-paginate="risk in Risks | itemsPerPage: 15">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div>
<dir-pagination-controls boundary-links="true" template-url="~/Scripts/AngularJS/Pagination/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</div>
</div>
</body>
</html>
you cannot use ng-click attribute on input with angularjs : https://docs.angularjs.org/api/ng/directive/input.
use onFocus javascript event
<input type="text" onfocus="myFunction()">
or try to surround your input with div or span and add ng-click on it.
I've got the working demo of your app, code (one-pager) is enclosed below, but here is the outline:
removed everything concerning dirPagination directive, replaced by ngRepeat
removed $log and replaced by console.log
since I don't have a Web API endpoint, I just populated $scope.Risks with some items on a rejected promise
Try adjusting your solution to first two items (of course, you won't populate it with demo data on rejected promise)
<!doctype html>
<html lang="en" ng-app="OpenBoxExtraModule">
<head>
<meta charset="utf-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module("OpenBoxExtraModule", []);
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi");
}
});
app.controller("RiskController", function ($scope, OpenBoxExtraService) {
//On load
GetAllRisks();
function GetAllRisks() {
var promiseGet = OpenBoxExtraService.getAllRisks();
promiseGet.then(function (pl) { $scope.Risks = pl.data },
function (errorPl) {
console.log("Some error in getting risks.", errorPl);
$scope.Risks = [{RiskID: "1", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "2", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"}, {RiskID: "3", i3_n_omr: "a", i3_n_2_uwdata_key: "b", RiskReference: "c", PureFacultative:"d", TimestampColumn: "e"} ];
});
}
$scope.ash = function () {
alert("Bananarama!");}
});
</script>
</head>
<body>
<div ng-controller="RiskController">
<table>
<thead>
<tr>
<th>Risk ID</th>
<th>i3_n_omr</th>
<th>i3_n_2_uwdata_key</th>
<th>Risk Reference</th>
<th>Pure Facultative</th>
<th>Timestamp</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="risk in Risks">
<td><span>{{risk.RiskID}}</span></td>
<td><span>{{risk.i3_n_omr}}</span></td>
<td><span>{{risk.i3_n_2_uwdata_key}}</span></td>
<td><span>{{risk.RiskReference}}</span></td>
<td><span>{{risk.PureFacultative}}</span></td>
<td><span>{{risk.TimestampColumn}}</span></td>
<td><input type="button" id="Edit" value="Edit" ng-click="ash()"/></td>
</tr>
</tbody>
</table>
<div>
<div></div>
</div>
</div>
</body>
</html>
Thank you all for your help, particularly #FrailWords and #Dalibar. Unbelievably, this was an issue of caching old versions of the javascript files. Doh!
You can't directly use then on your service without resolving a promise inside it.
fiddle with fallback data
this.getAllRisks = function () {
var d = $q.defer();
$http.get('/api/RiskApi').then(function (data) {
d.resolve(data);
}, function (err) {
d.reject('no_data');
});
return d.promise;
}
This will also fix your problem with getting alert to work.

bootstrap-table not rendering upon updating model in Angular

Hi I am not able to render table using bootstrap-table and angular. here is my code, I think I need to call bootstrap-table init method in angular ajax call. Can some one guide me on how to do this..?
angular
.module('reports')
.controller(
'ReportCtrl',
[
'$scope',
'$http',
'ngProgress',
function($scope, $http, ngProgress) {
var vm = this;
vm.mdp = {};
vm.mdp.data = [];
vm.mdp.columns = [];
$scope.submit = function() {
var report = $scope.tab;
$http.post('/reports/cmd/getData', {
report : report,
date : createdAfter
}).success(function(data) {
vm.mdp.data = data;
$.each(data[0], function(key, value){
vm.mdp.columns.push(key);
});
}).error(function(error) {
alert(error);
});
};
} ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mdp" class="panel" ng-controller="ReportCtrl as report" ng-show="panel.isSelected('mdp')">
<table data-toggle="table" data-show-columns="true" data-search="true" data-show-export="true" data-pagination="true" data-height="299">
<thead>
<tr>
<th ng-repeat="c in report.mdp.columns" data-field= {{c}} >{{ c }}</th>
</tr>
</thead>
<tr ng-repeat="r in report.mdp.data">
<td ng-repeat="c in report.mdp.columns">{{ r[c] }}</td>
</tr>
</table>
</div>
Integrating Bootstrap Table with Angular is solved here:
https://github.com/wenzhixin/bootstrap-table/issues/165
https://github.com/AkramKamal/bootstrap-table-examples/tree/master/integrate
I have some minor changes in my implementation of this solution which I will upload to Github / JSFiddle shortly. But the links above will allow you to get going.

Resources