Data isn't rendering in angular view - javascript

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

Related

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}}?

ng-click : pass data selectedItem between pages angularjs

So, I was able to select Items of my list, but the aim is to pass the data of the selected list in another /route when I click on it. I would need a bit of help because I don't really know how to proceed please. If you know punker examples do not hesitate to tell me :)
Bellow is my optionSuggestionController
app.controller('optionSuggestionController', ['$scope', '$http', function($scope, $http) {
$http.get('suggestions.json')
.then(function(res){
$scope.suggestions = res.data;
});
$scope.setMaster = function(suggestion) {
$scope.selected = suggestion;
}
$scope.isSelected = function(suggestion) {
return $scope.selected === suggestion;
}
}])
Bellow is my list of data
<ul class="list-holder">
<li ng-repeat="suggestion in suggestions" ng-class="{active : isSelected(suggestion)}">
<a ng-click="setMaster(suggestion)">{{suggestion.fromto}}</a>
</li>
</ul>
Bellow is my suggestions.json
[{ "fromto": "Dublin to London", "img": "http://placekitten.com/100/100" },
{ "fromto": "Dublin to Paris", "img": "http://placekitten.com/100/100" },
{ "fromto": "Dublin to Mexico", "img": "http://placekitten.com/100/100" }]
I think you can use the provider '$rootScope'.
$rootScope.selected = suggestion;
You can access this data in an other controller.
Hope it helps.
I have two suggestions:
You can use the provider '$rootScope'.
$rootScope.selected = suggestion;
Or get param via url by provider '$route'.
var suggestion = $route.current.params.suggestion;
You can use Service or Factory to share your data between controllers, I create a Factory with your codes and call it on a control to use.
app.controller('optionSuggestionController', function ($scope, $filter, $timeout, $timeout, $http, testFactory) {
testFactory.get(function (resp) {
console.log(resp);
$scope.suggestions = resp;
});
});
app.factory('testFactory', function ($http) {
var databaseFactory = {};
databaseFactory.get = function (callback) {
return $http.get('suggestions.json').then(function (response) {
databaseFactory.returnedData = response.data;
callback(databaseFactory.returnedData);
});
}
return databaseFactory;
});

select JSON object based on ui-router url

EDIT: Better phrasing of the question. I am basically looking at how to use the variable stored in $scope.item (grabbed from URL using $stateParams) to access the related object in the products JSON array.
Alright so I have used a combination of ui-router and ng-ref so that when you click a product on the "#/shop/" page it creates a URL "#/shop/productname" that when navigated to opens a blank div on the page that is meant to contain details about the product mentioned in the URL.
The issue I am having, and I'm sure there is something simple I am overlooking, is how to get the corresponding data based on the name in the URL? So that I can display product name/price etc that is stored in a JSON object?
Any help would help a ton! It's very possible I am going about this all wrong so please refer me in the right direction if you feel I could choose a better path.
HTML:
shop.html URL: #/shop
...
<a ng-repeat="item in businesses | filter:{cat: cat} | filter:query"
ng-class="{active: item.selected}"
ng-href="#/shop/{{item.link}}"
ng-click="selectedItem(item)">
...
</a>
<div ui-view></div>
...
product.html URL: #/shop/productName
<h1>item.name</h1>
<h2>item.price</h2>
App.js
angular.module('app', [
'ngAnimate',
'ui.router'
])
.config(function ($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/shop');
$stateProvider
.state('shop',{
url: '/shop',
templateUrl: 'templates/shop.html',
controller: 'starWarsCtrl'
})
.state('shop.item',{
url: '/:item',
templateUrl: 'templates/three-quarter-page.html',
controller: function($scope, $stateParams){
$scope.item = $stateParams.item;
}
})
;
})
.controller('appCtrl', function ($scope) {
$scope.products = [
{
"name": "Product 1",
"index":1,
"link":"product1",
"price":"TBD",
}
];
$scope.selectItem = function (selectedItem){
_($scope.products).each(function (item){
item.selected = false;
if (selectedItem === item){
selectedItem.selected = true;
}
})
};
}) /*End Controller*/
});
This will get the selected item for you, assuming you match by the name.
$scope.selectedItem = _.where($scope.products, {name: $scope.item});
I think, if I were you I would use angular service to share data between controllers
and this service will handle the data for me so when I change the product it will return the item object
angular.module('app').factory('productsService', function () {
self = this;
self.products = [{
"name": "Product 1",
"index":1,
"link":"product1",
"price":"TBD",
}];
this.findByLink = function(link){
// loop through your data
// returns what found or null
}
return {
products : this.products
findById : this.findById
}
});
and inject this service in each controller
.controller('appCtrl', function ($scope, productsService) {
$scope.products = productsService.products;
..........
and to anther one
.controller('productCtrl', function ($scope, productsService, $stateParams) {
$scope.item = productsService.findById($stateParams.link);
..........

AngularJS not displaying API data

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.

Making an $http.get or $http.jsonp call in Angular.js

I was given the following code to use to get the data I need, but it is not working for me. What am I doing wrong here. I have tried many things from the Angular.js docs and other stack overflow posts, but nothing has worked for me.
someurl
header: Content-Type = application/json
Pass in the following json:
{
"userID": "SomeUSER",
"password": "SomePSWD"
}
Below is the code I am using and it is not working.
function getGroup($scope, $http) {
$http.get('SOMEURL?callback=JSON_CALLBACK&userID=SomeUSER&password=SomePSWD ').
success(function(data) {
$scope.group = data;
});
}
this angularjs demo app show how to use http.jsonp
var httpJsonDemoController = angular.module('HttpJsonDemo', []);
httpJsonDemoController.controller('DataController', ['$scope', '$http', function($scope, $http) {
$http.jsonp("http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Waseem%20Hero").
success(function(data) {
$scope.data = data;
$scope.name = data.name;
$scope.salutation = data.salutation;
$scope.greeting = data.greeting;
}).
error(function (data) {
$scope.data = "Request failed";
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div id="wrapper" ng-app="HttpJsonDemo">
<div ng-controller="DataController">
<pre ng-model="data">
{{data}}
</pre>
<input ng-model='name' />
{{name}}
<input ng-model='salutation' />
{{salutation}}
<input ng-model='greeting' />
{{greeting}}
</div>
</div>

Categories

Resources