Console log image
Hi in my code below I am trying to convert xml Data to Json Object. Using converted Json Object I am trying to create a table using angularjs. So here the problem is I am able to bind complete converted json object {{employeeList}} but failed to load individual attribute of json object i.e., {{employee.EmpId}}. Finally from my observation I found when the converted json object is directly assigned to
$scope.Employees = {
"Employee": [{
"EmpId": "4",
"Name": "Chris",
"Sex": "Male",
"Phone": [{
"_Type": "Home",
"__text": "564-555-0122"
},
{
"_Type": "Work",
"__text": "442-555-0154"
}],
"Address": {
"Street": "124 Kutbay",
"City": "Montara",
"State": "CA",
"Zip": "94037",
"Country": "USA"
}
}]
};
the output is what I expected, but when I assign the direct result
i.e, $scope.Employees=response; it is not working. What might be the issue?
<script>
var app = angular.module('httpApp', []);
app.controller('httpController', function ($scope, $http) {
$http.get("File1.xml", {
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
console.log(response);
$scope.Employees = response;
console.log($scope.Employees);
});
});
<script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="httpApp">
<div ng-controller="httpController">
<div ng-repeat="employeeList in Employees">
{{employeeList}}
<table>
<tr ng-repeat="employee in Employees.Employee">
<td>{{employee.EmpId}}</td>
<td>{{employee.Name}}</td>
<td>{{employee.Phone._Type}}</td>
<td>{{employee.Phone.__text}}</td>
<td>{{employee.Address.Street}}</td>
<td>{{employee.Address.State}}</td>
<td>{{employee.Phone.Zip}}</td>
<td>{{employee.Phone._text}}</td>
<td>{{employee.Address.Country}}</td>
</tr>
</table>
</div>
</div>
</div>
Ok. The issue is, response.data after the conversion of the xml file has the following structure,
{
"Employees": { // note that the data you need is present in "Employees" field
"Employee": [
... // contains objects with employee details
]
}
}
So, you need to populate $scope.Employees as follows,
// your required data is present in "Employees" field of response.data
$scope.Employees = response.data.Employees;
So, your <script> tag code will be,
<script>
var app = angular.module('httpApp', []);
app.controller('httpController', function ($scope, $http) {
$http.get("File1.xml", {
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
// your required data is present in "Employees" field of response.data
$scope.Employees = response.data.Employees;
console.log($scope.Employees);
});
});
</script>
Here is the updated and working plunker.
Also, note that employee.Phone is an array and you need to use ng-repeat again to display the details as I've mentioned in one of the comments.
Related
I have 3 components, the web api, the controller, and the html. I can hit the web api just fine and i get back the results in JSON format, but when it then tries to render the JSON into the html, it looks like this.
{
"Projects": [{
"ProjectId": 1,
"Name": "Project1",
"Key": "Software",
"ProjectTypeKey": "1"
}, {
"ProjectId": 2,
"Name": "Project2",
"Key": "Hardware",
"ProjectTypeKey": "2"
}, {
"ProjectId": 3,
"Name": "Project3",
"Key": "Hardware",
"ProjectTypeKey": "3"
}]
}
WebApi
public IHttpActionResult Get()
{
listProjects.Add(new Project { ProjectId = 1, Name = "Project1", Key = "Software", ProjectTypeKey = "1" });
listProjects.Add(new Project { ProjectId = 2, Name = "Project2", Key = "Hardware", ProjectTypeKey = "2" });
listEmployeeProject.Add(new EmployeeProject {Projects = listProjects });
return Json(listEmployeeProject);
}
Controller
var myApp = angular.module('myApp', []);
myApp.service('dataService', function ($http) {
this.getData = function () {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: '/api/employee'
});
}
});
myApp.controller('ProjectController', function ($scope, dataService) {
$scope.Projects = [];
dataService.getData().then(function (result) {
$scope.Projects = result.data;
});
});
HTML
<div ng-app="myApp" ng-controller="ProjectController">
{{1 + 1}}
<div ng-repeat="project in Projects">
{{project}}
</div>
Even when i switch {{project}} to {{project.Name}}, nothing renders on the page.
console.log(results.data) looks like below
Its very clear from your console that you are returning an array of length 1 which has another array of length 3 in it
This is because of this line in your code
listEmployeeProject.Add(new EmployeeProject {Projects = listProjects });
Here you are retuning a EmployeeProject array and each element of that array has multiple projects. So do either of these things
a. Return listProjects like return Json(listProjects) (You should be returning Ok(model) ideally)
b. Or in angular promise do,
$scope.Projects = result.data[0].Projects;
I have JSON response from database query through controller and I would like to print this JSON object values in view.ejs file.
view.ejs
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.username}}</td>
<td>{{ x.password}}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("")
.then(function (response) {$scope.names = response.users;});
});
</script>
This is my Model
User.js
module.exports = {
autoCreatedAt: false,
autoUpdatedAt: false,
attributes: {
username:{
type:'string',
required: true,
unique:true
},
password:{
type:'string',
required:true
},
}
};
This is my controller
UserController.js
module.exports = {
get:function(req,res){
User.find().exec(function (err, users){
if (err) {
return res.json(err);
}
return res.json(users);
});
}
};
I am configuring routes in below file
routes.js
module.exports.routes = {
'/': {
view: 'view'
},
'/user/get': 'UserController.get',
};
when I hit URL "http://localhost:1337/user/get", I get this below json response and I want this values to be pushed into view.ejs file.
[
{
"username": "root",
"password": "root",
"id": 1
},
{
"username": "home",
"password": "home",
"id": 2
},
{
"username": "unisys",
"password": "unisys",
"id": 3
}
]
I would like to know if somebody can help me to understand how i can get these values.Thank you for any suggestion
The problem in assigning names from response data. i.e,
use
$scope.names = response.data.users; OR $scope.names = response.data;
instead of
$scope.names = response.users;
In response itself you are getting array of objects so if you assign it directly to $scope.names , it will work.
if it helps you, just let me know .
$http.get("localhost:1337/user/get").then(function (response) {$scope.names = response;
console.log(response) ;
})
I need to iterate through nested json array which looks like that
[
{
"title": "EPAM",
"technologies": [
"PHP",
".net",
"Java",
"Mobile",
"Objective-C",
"Python",
"Ruby"
],
"location": "Belarus",
"city": "Minsk"
},
{
"title": "Parallels",
"technologies": [
"PHP",
"Java",
"C++",
"iOS Development",
"C#",
"Ember.js"
],
"location": "Russia",
"city": "Moscow"
}
]
What I want is to iterate through list of technologies in each company and then return a list of unique values. I failed, however, to access a single company in company arrays in the controller. It looks like this so far
var app = angular.module('app', []);
app.controller('CompaniesController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/companies.json').success(function(data) {
$scope.companies = data; // get data from json
$scope.techStack = []
$scope.companies = data.query(function(companies) {
console.log(companies); //I expected to see data here
});
});
}
]);
Apparently I'm doing something wrong.
Use angular's forEach:
var app = angular.module('app', []);
app.controller('CompaniesController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/companies.json').success(function(data) {
$scope.companies = data; // get data from json
angular.forEach($scope.companies, function(item){
console.log(item.technologies);
})
});
});
}
]);
If you need only to display nested array on UI, you can do that straight in view
e.g.
<tr ng-repeat="i in Items">
<td valign="top">{{i.Value}}</td>
<td valign="top">
<table>
<tr ng-repeat="c in i.Children">
<td>{{c.Value}}</td>
</tr>
</table>
</td>
</tr>
In order to loop through array in AngularJS, you can simply use angular.forEach. For example,
angular.forEach(companiesList, function(company) {
//Here you can access each company.
});
I have made a simple demo based on your code that list "Companies" and unique "Technologies".
DEMO
try this
var app = angular.module('app', []);
app.controller('CompaniesController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/companies.json').success(function(data) {
$scope.companies = data; // get data from json
$scope.techStack = []
angular.forEach($scope.companies, function(item){
$scope.techStack = item.technologies;
var uniqueTech = [];
for (var i = 0; i < $scope.techStack.length; i++)
{
if (uniqueTech.indexOf($scope.techStack[i]) == -1)
uniqueTech.push($scope.techStack[i]);
}
console.log("Unique Technologies : " + uniqueTech);
})
});
}
]);
user angular's foreach function for looping through data.
My json file is of the format:
{
"doc": {
"BandDatabase": {
"Artist1": {
"-name": "john",
"-instrument": "piano"
"Artist2": [
{
"-name": "tina",
"-instrument": "drums"
"Manager": {
"Person1": {
"-name": "abby"
}
I have my controller setup as :
myApp.controller('MyController', ['$scope', '$http', function ($scope, $http) {
$http.get('js/artists.json').success(function(data) {
$scope.artists = data;
});
How do I search for an element in the json format above? I am unable to display the name element on the webpage my doing the following:
<div ng-controller = "MyController">
<ul class="artists">
<li class="messages" ng-repeat="item in artists">
<div class="info">
<h1>{{item.name}}</h1>
</div>
I want to be able to display the name of Artist1 and Artist 2.
JSON.Parse is part of JavaScript use it to convert JSON into JavaScript Objects.
$http.get('js/artists.json').success(function(data) {
$scope.artists = JSON.Parse(data).artists;
});
BTW your JSON looks rather strange to me... I imagine it should look more like this:
{
"artists": [
{
"name": "kongor",
"instrument": "gitar"
},
{
"name": "Jacob",
"instrument:" "...",
"manager": {
"name": "Cole"
}
}
]
}
I am new to Angularjs and having trouble displaying data . i.e. Json array
This is the result of my rest service call:
{
"users": [{
"id": 1,
"firstname": "Naveen",
"lastname": "Dutt",
"email": "navee23ndutt12.vyas#gmail.com",
"telephone": "7829418456445355"
}]
}
And this is my controller:
app.controller('MyCtrl2', ['$scope', 'NFactory', function ($scope, NFactory) {
alert("here??");
$scope.bla = NFactory.query;
alert("here??" + $scope.bla);
NFactory.get({}, function (nFactory) {
$scope.allposts = nFactory.firstname;
})
}]);
This is my html:
<div>
<ul >
<li ng-repeat="user in bla"> {{ user.firstname }} </li>
</ul>
</div>
but it doesnt show anything on UI. what can be the problem? please suggest.
It happens because you call async task. I would wrap result with promise.
Here is basic simulation of async call:
Demo Fiddle
var app = angular.module('myModule', ['ngResource']);
app.controller('fessCntrl', function ($scope, Data) {
Data.query()
.then(function (result) {
console.log(result);
$scope.bla = result.users;
}, function (result) {
alert("Error: No data returned");
});
});
app.$inject = ['$scope', 'Data'];
app.factory('Data', ['$resource', '$q', function ($resource, $q) {
var data = {
"users": [{
"id": 1,
"firstname": "Naveen",
"lastname": "Dutt",
"email": "navee23ndutt12.vyas#gmail.com",
"telephone": "7829418456445355"
}]
};
//Actually we can use $resource
//var data = $resource('localhost/shfofx/PHP/Rest/alertLossDetails.php',
// {},
// { query: {method:'GET', params:{}}}
// );
var factory = {
query: function (selectedSubject) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
If $scope.bla in your case is
{"users":[{"id":1,"firstname":"Naveen","lastname":"Dutt","email":"navee23ndutt12.vyas#gmail.com","telephone":"7829418456445355"}]
then your template should look like this:
<ul >
<li ng-repeat="user in bla.users"> {{ user.firstname }} </li>
</ul>
Another way would be to change the code inside your Controller like this:
$scope.bla = NFactory.query.users;
and leave template as you have it.
If NFactory.query is string you need to parse it as JSON first.
$scope.bla=JSON.parse(NFactory.query);
and then
<ul >
<li ng-repeat="user in bla.users"> {{ user.firstname }} </li>
</ul>
Hope this will help...
Shouldn't it be a method call: NFactory.query() ?
Please show the NFactory source.
UPDATE: Try responding just array from server:
[{
"id": 1,
"firstname": "Naveen",
"lastname": "Dutt",
"email": "navee23ndutt12.vyas#gmail.com",
"telephone": "7829418456445355"
}]
and use NFactory.query()