Displaying JSON data with ng-bind shows [object object] - html

I'm new to angular js,I have 2 goals:
OnClick, display a single person's name from a JSON array,
Randomize name on every click
I'm stuck at the part where i need to pass the json data to the view: when i click the button i get [object object], [object object], [object object]
Could someone please assist?
[
{"name": "John"},
{"name": "Sue"},
{"name": "Sally"},
{"name": "Jim"},
{"name": "Bev"},
{"name": "Joe"},
{"name": "Jess"}
]
script
var peopleApp = angular.module('peopleApp', []);
idApp.controller('peopleCtrl', ['$scope', '$http', function ($scope, $http){
$scope.randomPerson = function(){
$http.get('js/people.json').
success(function(data) {
$scope.person = data;
console.log(data);
});
}
}]);
view
<div class="content">
<div ng-controller="peopleCtrl">
<p ng-bind="name"></p>
<button ng-click="randomPerson()">
Show random person's name
</button>
<p ng-bind="person"></p>
</div>
</div>

You need to show a simple value after to get a random object of your array.
Something like this:
var peopleApp = angular.module('peopleApp', []);
peopleApp.controller('peopleCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.data = [{
"name": "John"
}, {
"name": "Sue"
}, {
"name": "Sally"
}, {
"name": "Jim"
}, {
"name": "Bev"
}, {
"name": "Joe"
}, {
"name": "Jess"
}];
$scope.person = "";
$scope.randomize = function(count) { // This function returns a random number, between 0 to the $scope.data.length.
return Math.floor((Math.random() * count) + 0);
};
$scope.randomPerson = function() { // By using array.filter you can get a specific object.
$scope.person = $scope.data.filter(function(x) {
return x.name;
})[$scope.randomize($scope.data.length)]; // Getting the random object.
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="peopleApp" class="content">
<div ng-controller="peopleCtrl">
<p ng-bind="name"></p>
<button ng-click="randomPerson()">
Show random person's name
</button>
<p data-ng-bind="person.name"></p>
</div>
</div>
More simpler and better: Without using array.filter.
var peopleApp = angular.module("peopleApp", []);
peopleApp.controller("peopleCtrl", ["$scope", "$http",
function($scope, $http) {
$scope.data = [{
"name": "John"
}, {
"name": "Sue"
}, {
"name": "Sally"
}, {
"name": "Jim"
}, {
"name": "Bev"
}, {
"name": "Joe"
}, {
"name": "Jess"
}];
$scope.person = "";
$scope.randomize = function(count) { // This function returns a random number, between 0 to the $scope.data.length (count).
return Math.floor((Math.random() * count) + 0);
};
$scope.randomPerson = function() {
$scope.person = $scope.data[$scope.randomize($scope.data.length)]; // Getting the random object.
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="peopleApp" class="content">
<div ng-controller="peopleCtrl">
<p ng-bind="name"></p>
<button ng-click="randomPerson()">
Show random person's name
</button>
<p data-ng-bind="person.name"></p>
</div>
</div>

The reason this is happening is because you are sending an array of objects from the controller to your view.
And then you directly bind the array to a <p> tag. So the entire array is getting displayed with object as it is unparsed on your view..
try changing
<p ng-bind="person"></p>
To :
<p ng-bind="person[randomIndex].name"></p>
// here random index is a random number
// where range of random number generator is from 0 to length of person array
you can generate a random number on click of function like this. If you wanted to get between 0 and length of array, you would put:
Math.floor(Math.random() * person.length) + 0
OR More specifically something like this ....
$scope.randomPerson = function(){
$http.get('js/people.json')
.success(function(data) {
$scope.person = data;
var randomPersonIndex =Math.floor(Math.random() * $scope.person.length) + 0 ;
$scope.myRandomPerson = $scope.person[randomPersonIndex];
console.log(data);
});
And then on HTML you do ....
<p ng-bind="myRandomPerson.name"></p>
// here random index is a random number

Simple and easy just need to add "| json" with your function name.
for example
<p ng-bind="person | json"></p>

Related

AngularJS $http.get don`t get data from json file

I have next code in the controller
app.controller('controller', function ($scope, $routeParams, $http) {
$http.get('db.json').success(function(data) {
$scope.phone = data;
});
});
this is JSON file:
{
"title1" : "first title",
"title2" : "second title",
"title3" : "third title",
}
and then I try to print the data like this:
<h1>{{ db.title1 }}</h1>
but in the browser I see nothing. What am I doing wrong?
i fixed first problem but there is another one
this is in json file
"nameArr" : [
{
"title": "title",
"image": "images/img.png"
},
{
"title": "title",
"image": "images/img1.png"
},
{
"title": "title",
"image": "images/img2.png"
},
{
"title": "title",
"image": "images/img3.png"
}
]
and ng-repeat in html like this
<div class="item" ng-repeat="items in nameArr">
<img ng-src="{{ items.image }}">
<h1>{{ items.title }}</h1>
</div>
and again don`t show nothing
Two things: 1) the object you reference in the template should be declared right off, not in the callback, and 2) the data coming back is going to be a string, you will need to use angular.fromJson or JSON.parse to parse it into an object.
$scope.phone = {};
app.controller('controller', function ($scope, $routeParams, $http) {
$http.get('db.json').success(function(data) {
$scope.phone = angular.fromJson(data);
});
Also, in your template, you cannot get at this inside db, because you put it on phone:
<h1>{{ phone.title1 }}</h1>

How to display JSON data in html page using ng-repeat in AngularJS?

I have one JSON data how to display these data using ng-repeat?
I am new in angularJS. I dont how to to repeat nested in ng-repeat in angularJS
This is my JSON data.Please help me to show the outputs?
How to get these data using ng-repeat
customerId=56b6f841d085980f2241909c
name: Maxxwell
Total Product=2
Total Price=685 //(2*18.5)+240(3*(240*10/100))
createdOn: 07-Feb-2016 10:50:05 UTC
etc....
See $scope.orders is an array
I call an api and got this data
orderPromise.success(function(data, status, headers, config)
{
$scope.orders=
[
{
"customerId": "56b6f841d085980f2241909c",
"address": {
"name": "Maxxwell",
"city": "Texas",
"country": "USA",
},
"products": [
{
"productId": "569df8bcd08598371e9b5ad9",
"quantity": 2,
"productDetails": {
"itemId": "569df86dd08598371e9b5ad8",
"actualPrice": "18.5",
"offer": 0,
"modifiedOn": "19-Jan-2016 12:35:32 UTC"
}
},
{
"productId": "569f2d2dd085980ecfc8997b",
"quantity": 3,
"productDetails": {
"itemId": "569f294dd085980ecfc89971",
"actualPrice": "240",
"offer": 10,
"modifiedOn": "06-Feb-2016 09:09:46 UTC"
}
}
],
"createdOn": "07-Feb-2016 10:50:05 UTC"
}
]
});
I need to display this output using ng-repeat in html page
customerId=56b6f841d085980f2241909c
name: Maxxwell
Total Product=2
Total Price=685 //(2*18.5)+240(3*(240*10/100))
createdOn: 07-Feb-2016 10:50:05 UTC
:
:
I don't know its correct or not but its not working in my html page
Please correct me if it is wrong?
$scope.ordertemp=[];
$scope.orderval={};
var countval = $scope.orders.length;
for(var j=0;j<countval;j++)
{
$scope.orderval.buyerId = $scope.orders[j].customerId;
$scope.orderval.name = $scope.orders[j].address.name
$scope.orderval.totalitem = $scope.orders[j].products.length
var count = $scope.orders[j].products.length
var total = 0;
var save=0;
for(var i=0;i<count;i++)
{
var actualprice = 0;
var offer = 0;
var price = 0;
var quantity=0;
actualprice = $scope.orders[j].products[i].productDetails.actualPrice;
offer = $scope.orders[j].products[i].productDetails.offer;
quantity = $scope.orders[0].products[i].quantity;
price = actualprice - (actualprice * offer)/100
total = total + (price * quantity);
save = save +((actualprice/100)*offer)* quantity
}
}
$scope.orderval.totalprice = total;
$scope.orderval.save = save;
$scope.ordertemp.push($scope.orderval);
alert(JSON.stringify($scope.ordertemp));
When i alert this data will shown but its not repeated in my ui page Why?
Can i add any filter for using this to add Total price?
you can also do like this,First flatten your response as your need. Like below
$scope.orders=
[
{
"customerId": "56b6f841d085980f2241909c",
"address": {
"name": "Maxxwell",
"city": "Texas",
"country": "USA",
},
"products": [
{
"productId": "569df8bcd08598371e9b5ad9",
"quantity": 2,
"productDetails": {
"itemId": "569df86dd08598371e9b5ad8",
"actualPrice": "18.5",
"offer": 0,
"modifiedOn": "19-Jan-2016 12:35:32 UTC"
}
},
{
"productId": "569f2d2dd085980ecfc8997b",
"quantity": 3,
"productDetails": {
"itemId": "569f294dd085980ecfc89971",
"actualPrice": "240",
"offer": 10,
"modifiedOn": "06-Feb-2016 09:09:46 UTC"
}
}
],
"createdOn": "07-Feb-2016 10:50:05 UTC"
}
]
Now code for flatten the response
var myFinalArr = [];
for (index in $scope.orders) {
var obj = {};
var productSum = 0;
obj.customerId = $scope.orders[index].customerId;
obj.name = $scope.orders[index].address.name;
obj.city = $scope.orders[index].address.city;
obj.country = $scope.orders[index].address.country;
obj.createdOn = $scope.orders[index].createdOn;
obj.productCount = $scope.orders[index].products.length;
for (index2 in $scope.orders[index].products) {
productSum = parseFloat(productSum) + parseFloat($scope.orders[index].products[index2].productDetails.actualPrice);
if (index2 == ($scope.orders[index].products.length) - 1) {
obj.productSum = productSum;
}
}
myFinalArr.push(obj);
}
console.log(myFinalArr);// your final Arr
$scope.orders = myFinalArr;
})
In view use this
<div ng-repeat = "orderData in orders">
<div>CustomerId : {{orderData.customerId}}</div>
<div>Name : {{orderData.name}}</div>
<div>Total Product : {{orderData.productCount}}</div>
<div>Total Price : {{orderData.productSum}}</div>
<div>CreatedOn : {{orderData.createdOn}}</div>
</div>
You can do :
<div ng-repeat="order in orders">
<div>
customerId={{order.customerId}}
</div>
<div>
name:{{order.address.name}}
</div>
<div>
Total product={{order.products.length}}
</div>
</div>
And you'll need a function or a watch to get the total of your products.
If you give me a Plnkr or Jsfiddle link with a working sample I could probably provide a more complete answer if you need.
Happy coding!
try this
<div ng-repeat="(key, value) in orders">
<p>{{value.customerId}}</p>
<p>{{value.createdOn}}</p>
<p>{{value.address.name}}</p>
<div ng-repeat="(key, provalues) in value.products">
<p>{{provalues.quantity}}</p>
<p>{{provalues.productDetails.actualPrice}}</p>
</div>
</div>
To display json Data in html add json filter to your expression like
<div ng-repeat="order in revoluza = (orders | json)">
<div>
customerId={{order.customerId}}
</div>
<div>
name:{{order.address.name}}
</div>
<div>
Total product={{order.products.length}}
</div>
</div>
Please find the clear answer below
html part
<div ng-repeat="(key,value) in accounttypes">
<ul><li ng-repeat="account in value.services">{{account.types}}</li></ul>
</div>
js part
bankservice.findByaccounttype($scope.selectedservice).then(function(results)
{
$scope.accounttypes = results;
});
function bankservice($q)
{
var accountservice=[{"id":"1","title":"Savings Account","services":[{"types":"ATM card request"},{"types":"loan request"}]},
{"id":"2","title":"Current Account","services":[{"types":"cheque book request"},{"types":"ATM card request"}]},
{"id":"3","title":"Demat Account","services":[{"types":"loan request"},{"types":"ATM card request"}]}];
return {
findAll: function() {
var deferred = $q.defer();
deferred.resolve(accountservice);
return deferred.promise;
},
findByaccounttype: function (selectedservice) {
var deferred = $q.defer();
var results = accountservice.filter(function (element) {return selectedservice === element.title;
});
deferred.resolve(results);
return deferred.promise;
}
}
}

How to put form data into json file in angularjs

I am creating an application where I have to add the contacts from a form input. I want to add data from the form input field to my JSON file.
Unfortunately I am not able to find any solution for it until now. Kindly help in this regard. This is my controller code where the JSON object is also defined. I want to fetch the data from input filed to the JSON object array.
var contactManager = angular.module('contactManager', ['ngAnimate']);
// Contacts List Controller
contactManager.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.contacts = data;
//$scope.contacts = 'name';
});
}]);
// Contacts Details Controller
contactManager.controller('DetailsController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$scope.contact = [{
"name": "Stephen Radford",
"phone": "0123456789",
"address": "123, Some Street\nLeicester\nGH1 2SR",
"email": "stephen#email.com",
"website": "stephenradford.me",
"notes": ""
},
{
"name": "Alan Border",
"phone": "154648445",
"address": "457, Some Street\nBirmingham\nLM1 2AB",
"email": "stephen#email.com",
"website": "alanborder.me",
"notes": ""
},
{
"name": "Misbah ul Haq",
"phone": "8899556744",
"address": "458, Some Street\nFaisalabad\nFD1 2MH",
"email": "misbah#email.com",
"website": "misbah.me",
"notes": ""
}
];
$scope.contactId = $routeParams.contactId;
$scope.addNew = function() {
$scope.contact.push($scope.newData);
$scop.newData = null;
$scope.added = true;
};
}
]);
This is my form code. Where I am taking the input from a form
<form class="form-horizontal" ng-submit="addNew()" ng-controller="DetailsController">
<input ng-model="contact.name">
<input ng-model="contact.phone">
<input ng-model="contact.address">
<button>Click here to store data</button>
</form>
You need to send the object to data storedata function.
<button ng-click="storedata(obj)">Click here to store data</button>
Than, you can do it whatever you want.
$scope.storedata = function(obj) {
// obj is json
$post('/path_to_server', obj);
};

Use JSON data coming from WebApi in AngularJS application

I get some data from a WebApi, the answer (below the code to get the datas) is in JSON. But I can't access this result from angularJS. The datas look like :
{
"$id": "1",
"result": [
{
"$id": "2",
"name": "Français",
"code": "FR",
"id": 1
},
{
"$id": "3",
"name": "Néerlandais",
"code": "NL",
"id": 2
},
{
"$id": "4",
"name": "English",
"code": "EN",
"id": 3
}
]
}
But I get the error below when I try to display the result :
data.result is undefined
I get the data like this :
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http', dataService]);
function dataService($q, $http) {
return {
initFormCustomer: initFormCustomer
};
function initFormCustomer() {
return $http({
method: 'GET',
url: 'http://localhost:123456/api/forminit/customer/',
headers: {
},
transformResponse: transformCustomer,
cache: true
})
.then(sendResponseData)
.catch(sendGetCustomerError)
}
function sendResponseData(response) {
return response.data;
}
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data.result);
console.log(data.result[0]);
return transformed;
}
function sendGetCustomerError(response) {
return $q.reject('Error retrieving customer(s). (HTTP status: ' + response.status + ')');
}
}
}());
The controller :
(function () {
angular.module('myApp')
.controller('customerController', ['$location', '$scope', 'dataService', CustomerController]);
function CustomerController($location, $scope, dataService) {
var vm = this;
vm.languages = dataService.initFormCustomer();
}
}());
I think the transform function gets a json string that you have to deserialize before using it as an object... try sth like:
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data);
console.log(transformed.result[0]);
return transformed.result;
}
Additionally you may look at the docs https://docs.angularjs.org/api/ng/service/$http . There is some code showing how to append a transform to the default one (that do the deserialization and XSRF checks)

Print nested JSON array values in AngularJS with ng-repeat

I need to access the values of "city" and "nation" inside the array the following json file using AngularJS with ng-repeat.
This is my Json file:
[
{
"name": "first",
"location": [
{
"city" : "milan",
"nation" : "italy"
}
],
"visibility": 1
},
{
"name": "second",
"location": [
{
"city" : "new york",
"nation" : "usa"
},
{
"city" : "london",
"nation" : "uk"
}
],
"visibility": 1
}
]
My problem is that I need to get City and Nation as text string values, because I need to add them as css class name inside a tag, basically like this:
<div class="milan italy"></div>
<div class="new york usa london uk></div>
I'm not able to figure it out how to do this.
I tried with this code but nothing is shown:
<div ng-repeat-start="tile in tiles"></div>
<div class="mix {{ tile.location.city }} {{ tile.location.nation }}"></div>
<div ng-repeat-end></div>
Thank you in advance for your suggestions.
As #MattDionis said, you would need to specify ng-class, not just class. What you can try is using a function for ng-class. So you can do
<div ng-repeat="tile in tiles">
<div ng-class="getLocation(tile)"></div>
</div>
$scope.getLocation = function(tile) {
var resp = '';
for (var i = tile.location.length; i-- > 0;) {
resp = resp + tile.location[i].city + ' ' + tile.location[i].nation;
}
return resp;
}
I'm sure there's a better way to combine them than that, but that's what I came up with off-hand
First, you want to use ng-class rather than simply class to properly evaluate those bindings.
Also, tile.location appears to be an array of objects rather than simply an object. Therefore, {{ tile.location.city }} would not work, but {{ tile.location[0].city }} should.
The remaining issue would be how to loop through mutliple city/nation values within ng-class. I'll get back to you on that.
Please see demo below
You can create function to transform your array of object to string ie:
$scope.tostring = function (array) {
var res = "";
angular.forEach(array, function (obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " +obj[k];
}
}
});
return res;
};
var app = angular.module('app', []);
angular.module('app').controller('homeCtrl', homeCtrl);
homeCtrl.inject = ['$scope'];
function homeCtrl($scope) {
$scope.titles = [{
"name": "first",
"location": [{
"city": "milan",
"nation": "italy"
}],
"visibility": 1
}, {
"name": "second",
"location": [{
"city": "new york",
"nation": "usa"
}, {
"city": "london",
"nation": "uk"
}
],
"visibility": 1
}];
$scope.tostring = function(array) {
var res = "";
angular.forEach(array, function(obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " + obj[k];
}
}
});
return res;
};
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="homeCtrl">
<div ng-repeat="title in titles">
<h3 ng-class="tostring(title.location)">{{title.name}} My class is:*{{tostring(title.location)}}* </h3>
</div>
</body>
</html>