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

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>

Related

View doesn't load JSON

I'm working with Symfony 3, Angular JS and Twig. My problem comes when I try to generate a JSON in a view(html.twig).
My Model (MongoDB)
{
"_id" : ObjectId("5a1feb783e06fa060c0076b2"),
"contenido" : [
[
{
"type": "item",
"name": "Foo",
"id": 5
},
{
"type": "item",
"name": "Bar",
"id": 6
}
]
]
}
My Controller:
class Controlador extends Controller
{
// This method retrieve data (Document) from MongoDB
public function renderizar(Request $request)
{
...
$repository= $this->get('doctrine_mongodb')
->getManager()
->getRepository('AppBundle:Class');
$object = $repository->find('5a1feb783e06dfa060c0076b2');
$contenido = json_encode($object->getContenido());
$contenidoB = htmlentities($contenido);
$contenidoC = html_entity_decode($contenidoB);
$contenidoDef = json_decode($contenidoC);
return $this->render('view.html.twig', 'contenido' => $contenidoDef));
}
}
I want to generate that JSON in the view (inside the AngularJS's controller) in order to render a drag and drop panel from AngularJS.
My view
{% block body %}
<!doctype html>
<html >
<head>
<script>
angular.module("app").controller("NestedListsDemoController", function($scope)
{
$scope.models = {
dropzones: {
"A": [
{
"type": "container",
"name": "container",
"id": 4,
"columns": [
[
{
"type": "item",
"name": "Foo",
"id": 5
},
{
"type": "item",
"name": "Bar",
"id": 6
}
]
]
}
]
}
};
});
</script>
...
{% endblock %}
The Angular's controller doenst recognize the JSON in view if I use variable that contains that JSON.
dropzones: {
...
"A": {{ contenido|raw }}
}
or
dropzones: {
...
"A": {{ contenido }}
}
However, If I write the JSON in the view, it works. But I need to put the content from that variable. Any idea? Could anyone help me?
I solved the problem changing the string I would received in controller. When I retreive the document from MongoDB (I don't know why) comes with an extra double [ ] . Then, the drag and drop panel didn't recognize that JSON format...
To solve, first I removed them in controller, secondly I generated the JSON in the view as follows:
dropzones: {
"A": [ {{ contenido|raw }} ]
}
That's all, it works for me.
Use this:
dropzones = {{ contenido|json_encode|raw }};

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

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>

AngularJS getting in trouble with my JSON

I have got a JSON object from my website:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”},
}
and AngularJS to manage the dynamic content but it doesn't seem to be working:
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function () {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function (data, status) {
$scope.people = data;
});
};
}
Here is a JSFiddle.
Can anybody help me with displaying data?
#qqruza to get the callback working properly in your jsfiddle.net/1zuteco7, change the url to this:
http://test.eventident.com/api/last_posts/siteid=&callpage=1&perpage=10&callback=JSON_CALLBACK
Notice the JSON_CALLBACK in the end. The rest of your app will still not work though cause you are not picking the right bindings from the returned data in your repeat directive. Try console.log(data) in the success function to click through the returned object and get to the right paths.
There were a number of issues with your JSON, I have resolved them.
It had different types of quotes in there. I have replaced them with ".
It now looks like this:
[{         
"ID": "100",
"role": {            
"subscriber": true         
},
"first_name": "Test",
"last_name": "Test2",
"custom_fields": {            
"job_title": "subscriber"         
},
}, {   
"ID": "102",
"role": {            
"subscriber": true         
},
"first_name": "Test 3",
"last_name": "Test 4",
"custom_fields": {            
"job_title": "testing"         
},       
}]
Also, you were not referencing the model fields correctly in your view.
Here is the updated working fiddle: http://jsfiddle.net/kmmmv83y/1/
You had a comma at the end of the last property, that will typically error everything out, the below JSON should work:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”}
}

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>

retrieving data using Ember

as I go deeper into EmberJS, I got into this context where I need to use HTTP request. As a start, I tried to retrieve JSON data so I made a test page that returns JSON and I also verified that it is in JSON by deserializing it. No errors were encountered but there is no output at all. Below are the details of my code
application.js
App = Ember.Application.create({});
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://172.19.20.30/EmberTest/testApi.aspx'
});
event.js
App.Event = DS.Model.extend({
title: DS.attr('string'),
body: DS.attr('string')
});
router.js
App.Router.map(function () {
this.resource('events', {path: '/'});
});
App.EventsRouter = Ember.Route.extend({
model: function () {
return App.Event.find();
}
});
JSON output from host
{ "events": [{ "id": 1, "title": "test title", "body": "test body" },{ "id": 2, "title": "another title", "body": "another body" }] }
HTML
<script type="text/x-handlebars" data-template-name="events">
this is an example
{{#each e in model}}
<label>{{e.title}}</label><br />
{{/each}}
</script>
what could possibly be missing in my code? comments, opinions, suggestions are greatly appreciated
Looks like the return JSON is wrong.. it should be singular:
{ "event": [{ "id": 1, "title": "test title", "body": "test body" },{ "id": 2, "title": "another title", "body": "another body" }] }
When you do a find with Ember Data it should have the model name:
this.store.find('event') So Ember-data know where the return map to.
This will generate a URL http://host:port/event
If you are changing host it should just be the base URL you are changing and not absolute. So in your case:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://172.19.20.30/EmberTest'
});
Then the URL will become http://172.19.20.30/EmberTest/events