I am new in angular and I am trying to load json file and repeat it on index file but can get through that json to get the arrays for repeat
app.js
chatApp.controller('userCtrl', function ($scope, $filter, $http) {
var obj = {content:null};
$http.get('test.json').success(function(data) {
obj.content = data;
});
console.log(obj);});
json file
{"data":
{"result":"success","customers_list":[
{"Chat":
{
"name": "John",
"town":"LA"
}},
{"Chat":
{
"name": "Peter",
"town":"NY"
}}],"message":"The function is correctly"}}
I would like to get the name and town , any ideas how to go through data-> customer_list untill I get something like:
$scope.loadChat =[
{
"name": "John",
"town":"LA"
},
{
"name": "Peter",
"town":"NY"
}
];
You can use the built in map function:
chatApp.controller('userCtrl', function ($scope, $filter, $http) {
$scope.loadChat = [];
$http.get('test.json').success(function(data) {
$scope.loadChat = data.data.customers_list.map(function(chat) {
return chat.Chat;
});
});
});
The map() method creates a new array with the results of calling a
provided function on every element in this array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
tYou can display the name and town looping trough content.data.customers_list with ng-repeat.
controller:
chatApp.controller('userCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('test.json').success(function(data) {
$scope.content = data;
});
}]);
html:
<div ng-repeat="user in content.data.customers_list">
{{user.Chat.name}} {{user.Chat.town}}
</div>
Related
I have problem while parsing single json object.
Assume that the below data get from server
{
"root": {
"data": [
{
"name": "Raj",
"age": "22"
},
{
"name": "Janu",
"age": "22"
}
]
}
}
And my script is
Script.js
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("manydata.json")
.success(function(response) {
$scope.myDatas = response.root;
});
});
HTML
<div ng-repeat="i in myDatas.data">
Name: {{i.name}}
Age: {{i.age}}
</div>
I have no problem while the response data is more than 1. But If the response data is 1 then the json will be:
{
"root": {
"data": {
"name": "Raj",
"age": "22"
}
}
}
How to generically parse these json data ?
PLNKR: http://plnkr.co/edit/W4YK6BDtIBfVhnPpHVm1?p=preview
You need just slight change, check type of responsedata.root.data. If it is not array, convert it to array. Here is your code becomes.
Here is plnkr
// Code goes here
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("singledata.json")
.success(function(response) {
if(response.root.data && !(response.root.data instanceof Array )){
response.root.data=[response.root.data]
}
$scope.myDatas = response.root;
});
});
You can normalize incoming data to always be an array. It's convenient to use Array.prototype.concat method for this:
$http.get("singledata.json")
.success(function(response) {
$scope.myDatas = response.root;
$scope.myDatas.data = [].concat($scope.myDatas.data);
});
Demo: http://plnkr.co/edit/UUWtDBK8qID1XoYeMXhu?p=preview
I would check if data is an array or not, and if not, just ammend the data to be an array:
Like this:
$http.get("singledata.json")
.success(function(response) {
if(response.root.data && !angular.isArray(response.root.data)){
var object = response.root.data;
response.root.data = [];
response.root.data.push(object);
}
$scope.myDatas = response.root;
});
You can check the whether the data is array or not. If not then you create the array as. Check this code its working.
For controller:
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("manydata.json")
.success(function(response) {
var data = response.root.data;
if(data.constructor === Array){
$scope.myDatas = data;
}else{
$scope.myDatas = new Array(data);
}
});
});
For html:
<div ng-repeat="i in myDatas">
Name: {{i.name}}
Age: {{i.age}}
</div>
Hope this helps.
This is an interesting question. I'm using a simple JSON Get request to get all the competetions according to date, and show result as a list.
the JSON response is kind of :
[
{
"id":33
"competition":565
},
{
"id":66
"competition":345
}
]
Then I should make another json request to get the name of each json item :
myserver.com/{id}
which look like :
{
"name":"Serie A"
}
I want to show a list of all the names of the competetions I have on the first json request according to date.
here is my angular js code for showing the list of a simple JSON request :
<div ng-controller="customersCtrl">
<ul>
<li ng-repeat="m in matches">
{{ m.id }}
</li>
</ul>
</div>
<script>
var app = angular.module('starter', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://Myserver.com/matches?date=2015-05-19")
.success(function (response) {$scope.matches = response;});
</script>
You can iterate through the matches and get the names with a new call:
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://myserver.com/matches?date=2015-05-19")
.success(function (response) {
$scope.matches = response;
for (var i = 0; i < response.length; i++) {
setName($scope.matches, i);
}
});
var setName = function (matches, index) {
$http.get("http://myserver.com/" + matches[index].id)
.success(function (response) {
matches[index].name = response.name;
});
}
});
Below code will first fetch all the competitions and then using their ids it will fetch names all the events parallely. it will give all the competition with details in one go only.
Warning: If you have large numbers of all competition then it will make same number of calls to get competition details all of them.
app.service('competition', function($http) {
this.getAllCompetitions = function() {
var baseUrl = 'http://Myserver.com';
return $http.get(baseUrl + '/matches?date=2015-05-19')
.then(function(allCompetitions) {
/* sample `data`
[
{
"id":33
"competition":565
},
{
"id":66
"competition":345
}
]
*/
var qArr = [];
allCompetitions.forEach(function(competition, index) {
var promise = $http.get(baseUrl + '/' + competition.id)
.then(function(competitionDetail) {
/* sample `competitionDetail`
{
"name":"Serie A"
"competition":565
}
*/
return {
competitionDetail: competitionDetail,
index: index
};
});
aArr.push(promise);
});
return $q.all(qArr).then(function(listOfData) {
listOfData.forEach(function(item) {
allCompetitions[item.index] = angular.extend(allCompetitions[item.index], item.competitionDetail);
});
return allCompetitions;
});
});
}
});
I am trying to display nested JSON in a page. I'm not sure how to drill down into it.
In my app js file I have an parameter called initialData that I want to call a function getProducts() when the view is called...
'use strict';
var quoteApp = angular.module('quoteApp', ['ui.router']);
quoteApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'ng-views/choose.html',
controller: "quoteBuilderController",
resolve: {
initialData: ['quoteApi', function (quoteApi) {
return quoteApi.getProducts();
}]
}
})
});
my quoteApi looks like this in case you want to see it...
(function () {
'use strict';
angular.module('quoteApp').factory('quoteApi', quoteApi);
quoteApi.$inject = ['$http'];
function quoteApi($http) {
var service = {
getProducts: getProducts,
getPrices: getPrices
};
var baseUrl = 'http://www.website.com/api/Pricing';
return service;
function getProducts() {
return httpGet('/GetProductCatalogue');
}
function getPrices() {
return httpGet('/GetPrices');
}
/** Private Methods **/
function httpExecute(requestUrl, method, data){
return $http({
url: baseUrl + requestUrl,
method: method,
data: data,
headers: requestConfig.headers }).then(function(response){
return response.data;
});
}
function httpGet(url){
return httpExecute(url, 'GET');
}
}
})();
So quoteApi.getProducts() returns JSON that looks like this...
{
"Cat1": [
{
"product_id": 1,
"product_name": "Prod1"
},
{
"product_id": 2,
"product_name": "Prod2"
}
],
"Cat2": [
{
...
}
]
}
My controller for the view looks like this...
(function () {
'use strict';
angular.module('quoteApp').controller('quoteController', ['$scope', '$http', '$timeout', quoteController]);
quoteController.$inject = ['initialData', 'quoteApi'];
function quoteController($scope, initialData) {
$scope.cat1Products = initialData;
};
})();
So my question is, how can I get 'initialData' to load products from Cat1 only? Should I try to do this from the html? It seems like it should be straight forward enough but I can seem to get it. Thank you.
You need to transform your response from your http request further so you only return the piece you require, and you may also want to consider using the .then() approach:
$http.get('/someUrl').then(function(response) {
//Do something with response.data.Cat1 here
}, function(errResponse) {
console.error('Error while fetching data');
});
Just take out cat1 from your initialData object
function quoteController($scope, initialData) {
$scope.cat1Products = initialData['Cat1'];
};
I'd like to filter the JSON being displayed by the route param provided. I have a list page which displays all of the json data and a detail page which I would like to just display the json matching the id in the routeparam.
This is my service:
app.factory("HC", ["$resource", function($resource) {
return {
API: $resource('/api/hc')
}
}]);
This is my controller which is working for displaying all of the results. How could I filter these by the requestParams?
app.controller('servicesDetail', ['$scope', 'HC', '$resource', '$routeParams', function ($scope, HC, $resource, $routeParams ) {
HC.API.query(function(results) {
$scope.services = results;
});
$scope.services = []
}]);
And here are my routes
.when('/services', {
templateUrl: 'templates/services.html',
controller: 'servicesController'
})
.when('/services/:serviceId', {
templateUrl: 'templates/servicedetail.html',
controller: 'servicesDetail'
})
Your json is not valid but in case it has format like that :
{ "_id" : "53bc36b8b7bbbf77208dec62", "name" : "this is from the client", "__v" : 0 }
you can use filterFilter service please see demo here http://jsbin.com/somob/1/edit?html,js,output
but the best option is send serviceId to server and get a single service from server instead array of services and filter them after
app.controller('servicesDetail', ['$scope', 'HC', '$resource', '$routeParams', 'filterFilter',
function ($scope, HC, $resource, $routeParams, filterFilter) {
$scope.services = [];
HC.API.query(function (results) {
$scope.services = results;
});
$scope.serviceId = $routeParams.serviceId;
$scope.serviceById = filterFilter($scope.services, {
_id: $routeParams.serviceId
});
}]);
html:
<!--just for testing -->
<p>ServiceId : {{serviceId }}</p>
<pre>{{serviceById |json}}</pre>
I have some JSON e.g.
[{
'name': 'test',
'phone': '012345678',
'date': '02/03/2014'
},
{ ... }
]
A controller something like :
var app = angular.module('App', []);
app.controller('NameListCtrl', function($scope, $http) {
$http.get('/api/v1/names.json').success(function(names) {
$scope.names = names;
});
});
HTML/JADE something like :
div#names(ng-controller="NameListCtrl")
li.course_list(ng-repeat="name in names | orderBy:'date1'")
span
{{name.date}}) // I want to do some formatting on this
span
{{name.name}}
I would like to perform a formatting operation on each date, is there a way of doing so without using filters ? I have seen something using the $httpProvider.
A way to do it in the controller... insert your own filter func.
app.controller('NameListCtrl', function($scope, $http, $filter) {
$http.get('/api/v1/names.json').success(function(names) {
angular.forEach(names, function(item){
item.date = $filter('date')(item.date, "shortDate");
});
$scope.names = names;
});
});
You could also use jade and do:
{{name.date|date:'shortDate'}})