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.
Related
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.
I am getting some of objects from back-end. each of the object has the child array called 'phaseIds', it has multiple array of object, from the array i required to find the "name" existance according to the filter..
once i filtered, that object need to show in the page. I tried but i coun't get the result. any one help me with correct way to do this?
at present i am filter by students, but i am getting all the objects without filtered.
var app = angular.module('myApp', []);
var projects = [
{"name":"one", "PhaseIds":[
{id:"1",name:"school"},
{id:"2",name:"student"},
{id:"3",name:"teacher"}
]},
{"name":"two", "PhaseIds":[
{id:"1",name:"school"},
{id:"3",name:"teacher"}
]},
{"name":"three", "PhaseIds":[
{id:"1",name:"school"},
{id:"2",name:"student"}
]},
{"name":"four", "PhaseIds":[
{id:"1",name:"school"},
{id:"3",name:"teacher"}
]},
{"name":"five", "PhaseIds":[
{id:"1",name:"school"},
{id:"3",name:"teacher"}
]}
]
app.controller('MainCtrl', function($scope) {
$scope.projects = angular.forEach( projects, function (project) {
var filteredProject = project;
angular.forEach( project.PhaseIds, function ( phase ) {
if(phase.name.toLowerCase().indexOf('student') > -1 ){
//only required the students avilable projects
return filteredProject;
}
})
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
<ul>
<li ng-repeat="project in projects">{{project.name}}</li>
</ul>
</div>
Live Demo
You needn't put the logic in your controller code. You can achieve it in your HTML snippet as well by using $filter. Check below example. You can make your filter structure as deeper as you want.
<ul>
<li ng-repeat="project in projects | filter:{ PhaseIds : { name : 'student' } }">{{project.name}}</li>
</ul>
Please check your plunker. I've updated it
I prefer the #Vineet solution but if you need to play with the Json from the controller the right code should be:
app.controller('MainCtrl', function ($scope) {
$scope.projects = [];
angular.forEach(projects, function (project) {
var filteredProject = project;
angular.forEach(project.PhaseIds, function (phase) {
if (phase.name.toLowerCase().indexOf('student') > -1) {
//only required the students avilable projects
$scope.projects.push(filteredProject);
}
})
})
});
You can see the solution here - http://plnkr.co/edit/seIfZlhIbUnYMhWdEpGr
var filterProjectData = function(projects) {
var filteredProjects = [];
angular.forEach( projects, function (project) {
angular.forEach( project.PhaseIds, function ( phase ) {
if(phase.name.toLowerCase().indexOf('student') > -1 ){
//only required the students avilable projects
filteredProjects.push(project);
}
});
});
return filteredProjects;
}
$scope.projects = filterProjectData(projects);
No brainier . I simply tweaked your foreach logic.
try this one
app.controller('MainCtrl', function($scope) {
$scope.projects = [];
angular.forEach( projects, function (project) {
var filteredProject = project;
angular.forEach( project.PhaseIds, function ( phase ) {
if(phase.name.toLowerCase().indexOf('student') > -1 ){
//only required the students avilable projects
$scope.projects = $scope.projects.concat(filteredProject)
}
})
})
});
Hre is the Plunker
EDIT :
using concat you will get object structure like this as per your requirement.
[ {"name":"one", "PhaseIds":[
{id:"1",name:"school"},
{id:"2",name:"student"},
{id:"3",name:"teacher"}
]},
{"name":"three", "PhaseIds":[
{id:"1",name:"school"},
{id:"2",name:"student"}
]}
]
And using push you will get like this
[0: [{
"name": "one",
"PhaseIds": [{
id: "1",
name: "school"
},
{
id: "2",
name: "student"
},
{
id: "3",
name: "teacher"
}]
}],
1: [{
"name": "three",
"PhaseIds": [{
id: "1",
name: "school"
},
{
id: "2",
name: "student"
}]
}]]
I am working on a project, where I have a list of items present at backend. I have to get that list items via get request and display to my view as a list items. (User can select multiple entries from the list). I got the list items from server to my angular controller. For this project I am using Angular material design. How can I display these list items from controller to view via angular material element, which is able to select multiple entries from the list?
Here is a code example,
angular.module('myApp').factory('searchService', function($log, $http) {
return {
getTaxonomie: function() {
var promise = $http.get("http://espri-host179:8586/callrec/getTaxonomy")
.success(function(response) {
$log.debug("successfully got Taxonomie");
return response;
console.log(" i am from service");
})
.error(function(error) {
$log.error("searchService.getTaxonomie error:" + error);
return {};
});
return promise;
}
};
});
I have created a service to get data from server and now i have to add it to the controller and then display to my view. Right now my controller and view are empty because i don't know how to proceed further.
Any help would be appreciated, Thanks.
here's a basic example on how to iterate on data recieved from a factory:
javascript:
app.controller('MainCtrl', function($scope, dataFactory) {
dataFactory.getData().then(function(res) {
$scope.people = res.data;
})
});
app.factory('dataFactory', function($http) {
var vm = this;
vm.getData = function() {
return $http.get('data.json');
};
return vm;
});
html:
<div ng-repeat="person in people">
{{$index}}: {{person.name}} is {{person.age}} years old
</div>
data.json:
[
{ "name": "john", "age": 19 },
{ "name": "john2", "age": 20 },
{ "name": "john3", "age": 21 }
]
here's an example plnkr
I have a multi check box application which requires me to have multiple filters. I have been unable to use multiple filters even if I try to hard code an array to filter on. Here is an example I have created to try to make this work.
Working Example
HTML MARKUP:
<body ng-app="app">
<div ng-controller="MainCtrl">
<div ng-repeat="item in data.sessions | IndustryFilter : data.sessions.industry ">
{{item.id}}
</div>
</div>
Javascript
var app = angular.module("app", [])
.controller("MainCtrl", function ($scope, MatchedFilterList) {
$scope.data = {"sessions": [{
"id": "a093000000Vhzg7AAB",
"industry": ["Automovtive"],
"sessionName": "Keynote",
},
{
"id": "a093000000zg7AAB",
"industry": ["Automovtive", "Retail"],
"sessionName": "Keynote2",
},
{
"id": "a093er000f00zg7AAB",
"industry": ["Automovtive", "Retail", "Consumer Goods"],
"sessionName": "Keynote3",
}
]};
}).filter("IndustryFilter", function (MatchedFilterList) {
return function () {
var filtered = [];
angular.forEach(MatchedFilterList.industry, function (item) {
filtered.push(item);
});
console.log("Filter: Filter " + filtered)
return filtered;
};
})
.factory("MatchedFilterList", function(){
var matchedFilterList = {};
matchedFilterList.industry = {
"Automotive": "Automotive",
"Retail" : "Retail"
};
return matchedFilterList;
});
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()