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"
}
}
]
}
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 have function to remove item in multiple array angularjs. i use a factory like bellow
app.factory("array_obj", function () {
var currentUserIDs = {};
currentUserIDs.data = [];
currentUserIDs.city = [];
return currentUserIDs;
});
in controller have a function like this
$scope.deleteItem = function (index) {
currentUserIDs.city.splice(index, 1);
setUserID(); //insert data in url realtime
}
this work just for one array like city
i need a function to delete any item in array_obj
function simpleController($scope) {
$scope.data = {
"results1": [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Beispiel" }, { "id": 3, "name": "Sample" } ] ,
"results2": [ { "id": 1, "name": "Test2" }, { "id": 2, "name": "Beispiel2" }, { "id": 3, "name": "Sample2" } ]
}
;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app>
<body ng-controller="simpleController">
<div data-ng-repeat="results in data">
<div data-ng-repeat="result in results">>
{{result.name}}</br>
</div>
</div>
</body>
</html>
Have Fun..!!!
In your controller:
$scope.all_results = data.results1.concat(data.results2);
In your view
<whatever ng-repeat="item in all_results">{{ item.id }} - {{ item.name }}</whatever>
You could work with an extra <div> with ng-repeat attribute in your HTML where in my example results is your data.
<div>
<div ng-repeat="result in results">
<div ng-repeat="item in result">{{item.name}}</div>
</div>
</div>
ok this work ... i have function to remove item in multiple array angularjs. i use a factory like bellow
app.factory("array_obj", function () {
var currentUserIDs = {};
currentUserIDs.data = [];
currentUserIDs.city = [];
return currentUserIDs;
});
in controller have a function like this
$scope.deleteItem = function (index) {
currentUserIDs.city.splice(index, 1);
setUserID(); //insert data in url realtime
}
this work just for one array like city
i need a function to delete any item in array_obj
What i am trying to do is simple. A user enters a value, on button click, my JS calls a service to retreive my JSON data and perform a search on the value entered against the JSON and if a match is found, display the 'Owner'.
HTML:
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<input type="text" ng-model="enteredValue">
</br>
<button type="button" ng-Click="findValue(enteredValue)">Search</button>
</div>
</div>
JS:
angular.module('myApp', []).controller('MainCtrl', function ($scope, $http, getDataService) {
$scope.findValue = function(enteredValue) {
alert("Searching for = " + enteredValue);
$scope.MyData = [];
getDataService.getData(function(data) {
$scope.MyData = data.SerialNumbers;
});
}
});
angular.module('myApp', []).factory('getDataService', function($http) {
return {
getData: function(done) {
$http.get('/route-to-data.json')
.success(function(data) {
done(data);
})
.error(function(error) {
alert('An error occured');
});
}
}
});
My JSON:
{
"SerialNumbers": {
"451651": [
{
"Owner": "Mr Happy"
}
],
"5464565": [
{
"Owner": "Mr Red"
}
],
"45165": [
{
"Owner": "Mr Sad"
}
],
"4692": [
{
"Owner": "Mr Green"
}
],
"541": [
{
"Owner": "Mr Blue"
}
],
"D4554160N": [
{
"Owner": "Mr Loud"
}
]
}
}
Here's my fiddle: http://jsfiddle.net/oampz/7bB6A/
I am able to call my service, and retrieve the data from the JSON, but i am stuck on how to perform a search on my retrieved data against the value entered.
Thanks
UPDATE:
The following finds a serialnumber entered:
angular.forEach($scope.MyData, function(value, key) {
if (key === enteredValue) {
console.log("I Found something...");
console.log("Serial: " + key);
console.log("Owner: " + key.Owner);
}
})
I can display the found serialNumber via console.log("Serial: " + key); but trying to display the Owner as console.log("Owner: " + key.Owner); is showing as Undefined.
The key is just to iterate over the data object while observing the correct structure for accessing the values.
Your search function could look like this:
$scope.results = [];
$scope.findValue = function(enteredValue) {
angular.forEach($scope.myData.SerialNumbers, function(value, key) {
if (key === enteredValue) {
$scope.results.push({serial: key, owner: value[0].Owner});
}
});
};
Notice that I'm pushing the results into an array. You can setup an ng-repeat in the view which will use this to present a live view of the results:
<input type="text" ng-model="enteredValue">
<br>
<button type="button" ng-Click="findValue(enteredValue)">Search</button>
<h3>Results</h3>
<ul>
<li ng-repeat="result in results">Serial number: {{result.serial}}
| Owner: {{result.owner}}</li>
</ul>
Demo
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()