AngularJS not displaying API data - javascript

I am new to AngularJS. I am trying to retrieve firstname, lastname & State from an API, using a search functionality for a statecode, say, "DC" for ex.
I have modified to be simpler, and I still see no result on the page:
Here's my get:
function ItemsController($scope, $http){
$http.get("https://my.ncarb.org/Public/api/certification/search?statecode=dc")
.success(function(data, status, headers, config){
$scope.items = data;
});
}
Here's a sample of my api:
{
"data": [
{
"id": "14e1047c-b811-40f7-8a21-780ae5edf1ed",
"firstName": "Kent",
"lastName": "Abraham",
"city": "WASHINGTON",
"stateCode": "DC",
"countryCode": "USA"
},]
}
and here's my HTML:
<body ng-controller="ItemsController">
<h1>jSON Data</h1>
<table>
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
<td>{{item.firstName}}</td>
<td>{{item.stateCode}}</td>
</tr>
</table>
</body>
But my output, upon inspecting, getting a 200 OK status, but nothing gets displayed on the page...Any reason why ?
Attached - Screenshot of response in Dev tools

You are doing it wrong. $http.get returns a promise.
Here is the working sample.
HTML:
<div ng-app="app">
<div ng-controller="ItemsController">
<h1>jSON Data</h1>
<table>
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
<td>{{item.firstName}}</td>
<td>{{item.stateCode}}</td>
</tr>
</table>
</div>
</div>
Angular App & Controller:
var module = angular.module('app', []);
angular.module('app').controller('ItemsController', ['$scope', '$http', function ($scope, $http) {
$http.get('https://my.ncarb.org/Public/api/certification/search?statecode=dc').then(function (response) {
// this callback will be called asynchronously
// when the response is available
$scope.items = response.data.data;
}, function (response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}]);
Output:

data is complete response from the api.
Just do :
$http.get("https://my.ncarb.org/Public/api/certification/search?statecode=dc")
.success(function(data, status, headers, config){
$scope.items = data.data;
});
It will solve your problem :)

Why do you do a second $http.get() ? If the first one return the sample of the api it is useless because you should pass something that return a response in parameter of your $http.get()
Maybe you should make$scope.states = response.data just after the call of your API.

Related

How to retrieve data from a json file using $Routeparams in angular JS

i'm facing problem to retrieve the data using $routeparams i will decscribe my problem
/Retriving the URL to redirect/
console.log($routeParams);
console.log($routeParams.json_url);
$.getJSON("./api-data/"+$routeParams.json_url, function(json){
$scope.data = json;
console.log('JSON--',$scope.data);
$scope.processdata();
});
/Retriving the URL to redirect/
this is how i tried to get the data but when i console it $routeparams having the data -> it is having the url in need
but when i concatenate with "json url" it shows "Failed to load resource: the server responded with a status of 404 (Not Found)" and "undefined" in the console
i'm sharing my app.js
app.js
App.config(['$routeProvider',function($routeProvider, $routeParams) {
$routeProvider
.when('/base-product/:json_url?', {
templateUrl :'templates/base_product.html',
controller :'BaseProductController'
})
my menu.html
this is the menu i have when i click on the particular link in this menu it should redirect to the associated json file dynamically
<ul id="submenu-2" class="collapse" >
<span ng-repeat="item in itemDetails">
<li><a href="#base-product?{{item.path}}" > {{item.title}}</a></li>
</span>
</ul>
my action.json will look like this
[
{
"title":"View",
"path":"actions/view.json",
"urlpath":"view?segment=view",
"apiPath":"api/view",
"methodType":"post"
},
{
"title":"Add",
"path":"actions/add.json",
"urlpath":"view?segment=add",
"apiPath":"api/add",
"methodType":"post"
},
]
i wrote a factory to fetch the array values from json file (action.json)
App.factory('itemsFactory', ['$http', function($http){
var itemsFactory ={
itemDetails: function() {
return $http(
{
url: "api-data/action.json",
method: "GET",
})
.then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
App.controller('SidenavItems_controller', ['$scope', 'itemsFactory', function($scope, itemsFactory){
console.log("Loading json array name is working fine and tested in console")
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
$scope.select = function(item) {
$scope.selected = item;
}
$scope.selected = {};
}]);
help me out with this ..thanks in advance
Your url param is wrong and you don't need to use '?' mark. Change it to
View
<li><a href="#base-product/{{item.path}}" > {{item.title}}</a></li>
Js
.when('/base-product/:json_url', {...}

div in ng-repeat is not getting updated?

I am getting a response from http get request and Iam using the response to iterate in the data
<div id="container" ng-app="myApp" ng-controller="myctrl">
<div ng-repeat="profile in profiles">
<p>{{profile.username}}</p>
</div>
</div>
This is for adding one profile on click
<input ng-click="addProfile()" type="button" value="add Profile" />
Here is my get request in the controller
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope, $http) {
$scope.profiles = [];
$http.get("test1.json")
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
alert("af");
$scope.items = response.data.profiles; //Response is provided below
$scope.profiles.push($scope.items);
console.log($scope.profiles); //gives the update Array
});
});
});
response of my get request of test1.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 1",
},
{
"type": "Student ",
"username": "Username 2",
}
]
}
response of my get request of test2.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 4",
},
{
"type": "Student ",
"username": "Username 5"
}
]
}
I have tried console.log after updating in the array.The array is updated but the div in ng-repeat is not getting updated?
Please close your JSON calling request by putting ')' at the end. There is no error apart from this and the same code works for me fine.
// Code goes here
var myApp = angular.module("myApp", []);
myApp.controller("myctrl", function($scope, $http) {
$http.get('test1.json')
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
$scope.items = response.data.profiles; //Response is provided below
angular.forEach($scope.items, function(value) {
$scope.profiles.push(value);
});
console.log($scope.profiles);
});
};
});
Please find this updated js code and check. Once it is fixed let me know. happy coding :)
First of all I don't think you need $scope.$apply() to trigger the digest cycle. You are in angular context.
Second, you are missing a ')' when you are calling .then(). You currently have '.then(function(){};'
Third, your response object should not have a comma after the username property if that property is the last one in the object.
Also do you have a silent fail, or it is an error in the console, and the processed html for the ng-repeat is blank or you get the angular interpolation syntax {{profile.username}}?

Data isn't rendering in angular view

When I try to access test json data, it retrieves the data. however it won't display within my template
app.js:
var listController = angular.module('ngAppListDemo', []);
listController.controller('listControl', ['$scope', '$http', function ($scope, $http){
$scope.list = [];
var urlTest = 'https://mysafeinfo.com/api/data?list=englishmonarchs&format=json'; // url
//var testData = 'http://raw.githubusercontent.com/zemirco/sf-city-lots-json/master/citylots.json'; // .json format
$http({method: 'GET', url: urlTest}).success(function(data, status, headers, config) {
$scope.list = data;
console.log(data);
});
}]);
index.html
<div ng-app="ngAppListDemo">
<div ng-controller="listControl">
<div class="row" ng-repeat="item in list">
<p>{{item.nm}}</p>
</div><!-- end list item -->
</div>
</div>
data looks like this within url:
[
{
"nm": "Edmund lronside",
"cty": "United Kingdom",
"hse": "House of Wessex",
"yrs": "1016"
},
{
"nm": "Cnut",
"cty": "United Kingdom",
"hse": "House of Denmark",
"yrs": "1016-1035"
},
{
"nm": "Harold I Harefoot",
"cty": "United Kingdom",
"hse": "House of Denmark",
"yrs": "1035-1040"
}
]
It's repeating within the template fine. but the data inbetween the <p> tags {{ item.nm }} doesn't show. What am I missing?
Edit: It appears that ng-binding is missing once rendering.
working example : http://plnkr.co/edit/DeO5fmub16hXutOmylBu?p=preview
try this
var listController = angular.module('ngAppListDemo', []);
listController.controller('listControl', ['$scope', '$http', function ($scope, $http){
$scope.list = [];
var urlTest = 'https://mysafeinfo.com/api/data?list=englishmonarchs&format=json'; // url
//var testData = 'http://raw.githubusercontent.com/zemirco/sf-city-lots-json/master/citylots.json'; // .json format
$http({
method: 'GET',
url: urlTest
}).then(function successCallback(response) {
// the data is in response.data (or data.data using your old paramater name) not data directly
$scope.list = response.data;
console.log(response.data);
// update 1
$scope.$apply();
}, function errorCallback(response) {
});
}]);
// update 1: try a $scope.$apply() to force the view to update
Seems to be working fine. Created a demo
using same html
<div ng-app="ngAppListDemo">
<div ng-controller="listControl">
<div class="row" ng-repeat="item in list">
<p>{{item.nm}}</p>
</div><!-- end list item -->
</div>
</div>
May be your css would be having the font and back ground colour same
After comparing dev inspection from answers with demos. I noticed that I was missing class="ng-binding".
I added :
<span ng-bind="item.nm"></span>
https://docs.angularjs.org/api/ng/directive/ngBind

AngularJS $watch not updating my output

I have an HTML which looks like -
<div ng-controller="PostsCtrl">
<ul ng-repeat="post in posts" style="list-style: none;">
<li style="padding: 5px; background-color: #f5f5f5;">
<h4>
{{post.postTitle}}
</h4>
<div class="post-details" ng-show="showDetails">
<p>{{post.postContent}}</p>
</div>
</li>
</ul>
</div>
Now the data is being populated from a JSON based REST URL and being displayed. I also have a form that will be adding new post to the database-
<form data-ng-submit="submit()"
data-ng-controller="FormSubmitController">
<h3>Add Post</h3>
<p>
Title: <input type="text" data-ng-model="postTitle">
</p>
<p>
Content: <input type="text" data-ng-model="postContent">
</p>
<p>
Tags: <input name="postTags" data-ng-model="postTags" ng-list
required>
</p>
<input type="submit" id="submit" value="Submit" ng-click="loadPosts()" /><br>
</form>
I basically want to achieve two things -
1. As soon as i add new post it shows up in the list of posts above.
2. As soon as i manually add a new post in the backend, front end automatically updates.
Is it possible to achieve both using angular and if yes how will i be able to do that.
Below is my controller code, which as of now is showing me existing posts as well as letting me add new post to DB.
<script>
var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
$http.get('http://localhost:8080/MyApp/posts')
.success(function(data, status, headers, config) {
$scope.posts = data;
}).error(function(data, status, headers, config) {
console.log("Error in fetching the JSON data.");
});
$scope.$watch('posts', function(newVal, oldVal){
console.log('changed');
alert('hey, myVar has changed!');
}, true);
/*$scope.$watch('posts', function() {
alert('hey, myVar has changed!');
console.log("test log");
$scope.$digest();
});*/
});
app.controller('FormSubmitController', [ '$scope', '$http',
function($scope, $http) {
$scope.loadPosts = function() {
$http.get('http://localhost:8080/MyApp/posts')
.success(function(data, status, headers, config) {
$scope.posts = data;
alert(JSON.stringify(data));
//$scope.posts_updated = data;
}).
error(function(data, status, headers, config) {
console.log("Error in fetching the JSON data.");
});
}
$scope.list = [];
$scope.submit = function() {
var formData = {
"postTitle" : $scope.postTitle,
"postContent" : $scope.postContent,
"postTags" : $scope.postTags,
"postedBy" : "admin"
};
var response = $http.post('addPost', formData);
response.success(function(data, status, headers, config) {
console.log("na");
});
response.error(function(data, status, headers, config) {
alert("Exception details: " + JSON.stringify({
data : data
}));
});
//Empty list data after process
$scope.list = [];
};
} ]);
</script>
Any help on this will be really appreciable.
1: on your success of post, you can just push the added object into your posts list. This will trigger the two-way-binding, and the object will "automatically" appear in your ng-repeater.
$scope.posts.push(element);
2: This one is a bit tricky, since angular is a client-side application, it doesn't recognize what happens on the server-side. What you have to do to make this work is to look at websockets (like SignalR or similar) that can make a push to your client whenever something gets added. This also depends on that your "manual" insert is done using a programatically method. Doing it directly from database-changes is going to be alot more painfull
Initialize $scope.posts before invoking $http request
$scope.posts = [];
Since you are using $http service, it should automatically repaint ng-repeat when new data found. So you don't need be to worried about it
Very important thing is that you don't need to call $digest when you use $http service. Using $digest blindly is a very bad practice and is major performance issue. In the end of $http service angular automatically call $digest so you don't need to call again

Angular $http service does not load json file

Hello angular experts!
I used this custom directive for a table (implementation) but when I try to use $http service load that json array from a file, json is not loaded into $scope.items, I am a beginner in angular and on fairly advance javascript thus I need some help from you.
controller initialization
fessmodule.controller('ptiListController', function($http, $scope, $filter) {
$http service call
$http.get('data/ptis/ptis.json').then(function(response) {
$scope.items = response.data;
}
);
browser console error
TypeError: Cannot read property 'length' of undefined
at Scope.$scope.groupToPages (http://localhost:8000/app/modules/app/phone/scripts/pti-list-controller.js:75:49)
at Scope.$scope.search (http://localhost:8000/app/modules/app/phone/scripts/pti-list-controller.js:68:16)
at new <anonymous> (http://localhost:8000/app/modules/app/phone/scripts/pti-list-controller.js:117:12)
at invoke (http://localhost:8000/app/lib/js/angular.js:4185:17)
at Object.instantiate (http://localhost:8000/app/lib/js/angular.js:4193:27)
at http://localhost:8000/app/lib/js/angular.js:8462:28
at link (http://localhost:8000/app/lib/js/angular-route.js:975:26)
at invokeLinkFn (http://localhost:8000/app/lib/js/angular.js:8219:9)
at nodeLinkFn (http://localhost:8000/app/lib/js/angular.js:7729:11)
at compositeLinkFn (http://localhost:8000/app/lib/js/angular.js:7078:13) <div ng-view="" class="ng-scope">
so what I have changed from the fiddle is:
instead of:
$scope.items = [
{"id":1,"name":"name 1","description":"description 1","field3":"field3 1","field4":"field4 1","field5 ":"field5 1"},
{"id":2,"name":"name 2","description":"description 1","field3":"field3 2","field4":"field4 2","field5 ":"field5 2"},
{"id":3,"name":"name 3","description":"description 1","field3":"field3 3","field4":"field4 3","field5 ":"field5 3"}
];
i have changed to this:
$http.get('data/ptis/ptis.json').then(function(response) {
$scope.items = response.data;
}
);
and also, I have tried using the service call as:
$http.get('data/ptis/ptis.json').success(function(data) {
$scope.items = data;
});
and got the same behavior.
Thank you in advance!
I believe you are using the $http.get wrong. Try $http.JSONP this pattern:
$scope.items = {}; // <-- initialize empty object
$http.jsonp('/someJSONUrl').
success(function(data) {
// this callback will be called asynchronously
// when the response is available
$scope.items = data; // <-- fill object with data
});
You can't use $scope.items before it holds some data. That's why you have to initialize it first, as empty object/array then fill it with data and angular magic should do the rest :)
I just do something like this as mention in document and it work:
$http.get('someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Here the sample:
angular.module('myApp', [])
.controller('JustCtrl', function($scope, $http) {
$scope.ptis = [];
// Simple GET request example :
$http.get('https://gist.githubusercontent.com/idhamperdameian/239cc5a4dbba4488575d/raw/0a2ea4c6c120c9a8f02c85afcf7a31941ef74d3a/ptis.json').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.ptis = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="JustCtrl">
<span ng-repeat="p in ptis">
{{p.name}}, {{p.description}}, etc...<br>
</span>
</div>
Or you may prefer to this demo.

Categories

Resources