2 Json document associate and nested in angularJS - javascript

I have two json. For example
1
[ {"id":"23", "name":"mehmet"} , {"id":"22", "name":"jack"} ]
2
[ {"id":"1", "userID":"23"} , {"id":"2", "userID":"23"}, {"id":"3", "userID":"22"}]
in the first json mehmet have 2 entries second json ( associate userID )
I want to...
mehmet (source first json)
id:1 (second json)
id:2 (second json)
jack(source first json)
id:3 (second json)
My controller:
.controller('ListviewCtrl', function($scope, $http, SERVER) {
$scope.topics = [];
function loadTopics(params, callback){
$http.get(SERVER.url+'/listtopic', {params: params})
.success(function(response){
var topics = [];
angular.forEach(response, function(result){
topics.push(result);
});
callback(topics);
});
};
$scope.tweetler = [];
function loadTweetler(params, callback){
$http.get(SERVER.url+'/tweet')
.success(function(response){
var tweetler = [];
angular.forEach(response, function(result){
tweetler.push(result);
});
callback(tweetler);
});
};
how to use ng-repeat and list associate 2 json ?

You can create a filter inside the child ng-repeat, as follows:
var app = angular.module('app', []);
app.controller('mainCtrl', function($scope) {
$scope.parents = [
{
"id":23,
"name":"mehmet"
},
{
"id":22,
"name":"jack"
}
];
$scope.childs = [
{
"id":1,
"userID":23
},
{
"id":2,
"userID":23
},
{
"id":3,
"userID":22
}
];
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<ul>
<li ng-repeat-start="parent in parents" ng-bind="parent.name"></li>
<ul ng-repeat-end ng-repeat="child in childs | filter: { userID: parent.id }">
<li ng-bind="'Id:' + child.id"></li>
</ul>
</ul>
</body>
</html>

Make one of that arrays to an object, then its easier to grab the data from it. To make it simpler take the 1:1 relationship array..
var users = [
{"id":"1", "name":"mehmet"},
{"id":"2", "name":"jack"}
]
// This is simple 1:1 relationship.. ID:NAME
{
"1": "mehmet",
"2": "jack"
}
// To do it, is very simple
$scope.users = {};
angular.forEach(users, function(user) { $scope.users[user.id] = user.name})
Then you can take the correct User by ID
<li ng-repeat="post in posts">
<span>Author: {{users[post.userId]}}</span>
</li>

Related

Angular js solve a different format of a json array of objects

Based on the result below , how can an angular for each loop be able to solve that json array of objects format ? The value is title and the id is key. Any Idea? Thank you.
mycode
me.record.questionaires = []
angular.forEach(detail.questionaires, function (value, key) {
me.record.questionaires.push({ "id": key, "title": value })
});
Formated json data (detail.questionaire result)
[
"{'sub_title': 'dsadsa', 'instruction': 'You Must',…elimit': '01:05:19', 'title': 'asdsa', 'id': 133}",
"{'sub_title': 'sdasdsa', 'instruction': None, 'cre…melimit': '05:30:09', 'title': 'asda', 'id': 131}"
]
You need to
Loop over the array
Parse the string as JSON
Push or map the appropriate values into your questionaires array (it's not clear what data you want)
me.record.questionaires = detail.questionaires.map(json => {
let { id, title } = JSON.parse(json)
return { id, title }
})
I had to change your sample formatted JSON a bit because it was giving me console errors. Please see if this helps.
angular
.module("myModule", [])
.controller("myController", function($scope) {
var me ={record: {questionaires: []}};
$scope.me = me;
var detail ={};
detail.questionaires = [
"{'sub_title': 'dsadsa', 'instruction': 'You Must','…elimit': '01:05:19', 'title': 'asdsa', id: 133}",
'{"sub_title": "sdasdsa", "instruction": "None", "cre…melimit": "05:30:09", "title": "asda", "id": 131}'
];
angular.forEach(detail.questionaires, function (value, key) {
var questionaire = JSON.parse(value.replace(/'/g, '"').replace(/id:/g, '"id":'));
me.record.questionaires.push({ "id": questionaire.id, "title": questionaire.title });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myModule">
<div ng-controller="myController">
<div><strong>me.record.questionaires:</strong></div>
<div ng-repeat="q in me.record.questionaires">
<div>{{q}}</div>
</div>
</div>
</div>

Displaying values from an array of objects AngularJS

can someone help me to bite it?
Problem is, that I have res with server string, array of orders
Array
[ Object, Object, Object ]
And wants to display the item's value from all objects one by one
example:
order 1 [
DELL
ziemniaki
Wisnie
111111111 ]
order 2 [
Wisnie
Ziemniaki
]
Controller:
$scope.ListOfOrders = function () {
return ApiService.cart.list($scope.user).then(function (resp) {
$scope.orders = JSON.parse(resp[0].order);
console.log(resp)
});
}
in {{orders}} is
> [{"_id":"596f39515156f6178cbf3721","order":"[{\"item\":\"DELL\",\"quantity
> \":6,\"price\":144},{\"item\":\"ziemniaki\",\"quantity\":3,\"price\":3131},
> {\"item\":\"Wisnie\",\"quantity\":1,\"price\":31},{\"item\":\"111111111\",\"quantity\":1,\"price\":13}]","price":10301,"client":"q","IDclient":"5969ef800151e63ce01ec50c","__v":0,"created":"2017-07-19T10:49:53.061Z","updated":"2017-07-19T10:49:53.061Z"},{"_id":"597085de1d3e9722385773a8","order":"[{\"item\":\"ziemniaki\",\"quantity\":2,\"price\":3131},{\"item\":\"Wisnie\",\"quantity\":5,\"price\":31}]","price":6417,"client":"q","IDclient":"5969ef800151e63ce01ec50c","__v":0,"created":"2017-07-20T10:28:46.591Z","updated":"2017-07-20T10:28:46.591Z"},{"_id":"597086e41d3e9722385773a9","order":"[{\"item\":\"ziemniaki\",\"quantity\":2,\"price\":3131},{\"item\":\"Wisnie\",\"quantity\":5,\"price\":31}]","price":6417,"client":"q","IDclient":"5969ef800151e63ce01ec50c","__v":0,"created":"2017-07-20T10:33:08.444Z","updated":"2017-07-20T10:33:08.444Z"}]
you can modify the data as per your requirement -
like you can do this.
var newOrders=[]
angular.forEach(orders,function(value,key){
var obj={};
obj.Ordername="Order"+key;
obj.values=[];
angular.forEach((value.order),function(v,k){
obj.values.push(v.item);
})
newOrders.push(obj);
})
Now this newOrder can be used as you want.
Hope it will help you.
You can filter the item from response to display -
app.controller('orderCtrl', ['$scope', 'ApiService', '$filter',
function(s, ApiService, $filter) {
s.newOrders = [];
//Function to get the order response
s.ListOfOrders = function () {
return ApiService.cart.list(s.user).then(function (resp) {
s.orders = JSON.parse(resp[0].order);
//Now everything in orders
s.orders.forEach(function(o) {
s.newOrders.orderName="Order"+key;
s.newOrders.items = o.filter(function(r) { return r.item })
console.log(s.newOrders )
})
});
}
}])
//In html template
<div ng-repeat="order in newOrders">
<span>order.orderName</span>
<div ng-repeat="item in order.items">
{{item}}
</div>
</div>

How to push data in angularjs

there is an issue when I'm adding data to list with a function called addGroup.It is giving me this type-error:
"TypeError: Cannot read property 'push' of undefined"
at r.$scope.addGroup (main.js:7)
at fn (eval at compile (angular.js:13365), <anonymous>:4:215)
at e (angular.js:23613)
at r.$eval (angular.js:16052)
at r.$apply (angular.js:16152)
at HTMLAnchorElement.<anonymous> (angular.js:23618)
at HTMLAnchorElement.dispatch (jquery.min.js:3)
at HTMLAnchorElement.q.handle (jquery.min.js:3)
(anonymous) # angular.js:12520
(anonymous) # angular.js:9292
$apply # angular.js:16157
(anonymous) # angular.js:23618
dispatch # jquery.min.js:3
q.handle # jquery.min.js:3
html code:
<ul ng-repeat = "info in infos | filter:curInfo.name">
<img src="{{info.image.link}}"/> {{info.name}}
<li ng-repeat="group in info.groups | filter: curInfo"
ng-bind-html="group.name | highlight:curInfo.name">
{{group.name}}
</li>
<div class="add list">
+Add group
</div>
</ul>
js code:
app.controller('mainCtrl', function($scope , dataService){
$scope.addGroup = function () {
var group = {name: "This is a new group"};
$scope.infos.push(group);
};
json data
[
{
"id":736,
"name":"Systems",
"image":{
"link":"http://i.stack.imgur.com/8KA9j.jpg?s=32&g=1"
},
"groups":[
{
"id":2168,
"name":"API",
"url":"https://wwww.itschools.co.za/api/"
},
{
"id":11955,
"name":"Assets",
"url":"https://wwww.itschools.co.za/assets/"
},
{
"id":3179,
"name":"Design",
"url":"https://wwww.itschools.co.za/design/"
},
{
"id":207,
"name":"Development",
"url":"https://wwww.itschools.co.za/development/"
},
{
"id":70,
"name":"Intranet",
"url":"https://wwww.itschools.co.za/intranet/"
}
],
"url":"https://wwww.itschools.co.za/projects"
},
{
"id":44315,
"name":"User Agents",
"image":{
"link":"http://www.zerohedge.com/sites/default/files/pictures/picture5781.jpg"
},
"groups":[
{
"id":191599,
"name":"Alchemy",
"url":"https://wwww.itschools.co.za/tools/alchemy"
},
{
"id":86822,
"name":"Empathy",
"url":"https://wwww.itschools.co.za/tools/empathy"
},
{
"id":86297,
"name":"Epiphany",
"url":"https://wwww.itschools.co.za/tools/epiphany"
},
{
"id":131837,
"name":"Harmony",
"url":"https://wwww.itschools.co.za/tools/hamony"
},
{
"id":174338,
"name":"Zagreb",
"url":"https://wwww.itschools.co.za/tools/zagreb"
}
],
"url":"https://wwww.itschools.co.za/tools"
}
]
I have used a navigation bar to show this data. the "groups" part is shown in and now I want the addGroup function to add new list items but it is added in ul tag.
The main issue seems to be an uninitialized $scope.infos variable. I'm guessing this variable's contents are fetched via your dataService service, and that your intention is to push to the groups member of some element of $scope.infos.
To do that, your addGroups will need to know which groups to push into, so either info or info.groups will need to be passed in as a parameter (I went with the latter).
Here's a pared down version of what I think you're trying to accomplish.
angular.module('app', [])
.factory('dataService', ['$q', function($q) {
//dummy service simulating actual dataService
var infos = [
{
"id":736,
"name":"Systems",
"image":{
"link":"http://i.stack.imgur.com/8KA9j.jpg?s=32&g=1"
},
"groups":[
{
"id":2168,
"name":"API",
"url":"https://wwww.itschools.co.za/api/"
},
{
"id":11955,
"name":"Assets",
"url":"https://wwww.itschools.co.za/assets/"
},
{
"id":3179,
"name":"Design",
"url":"https://wwww.itschools.co.za/design/"
},
{
"id":207,
"name":"Development",
"url":"https://wwww.itschools.co.za/development/"
},
{
"id":70,
"name":"Intranet",
"url":"https://wwww.itschools.co.za/intranet/"
}
],
"url":"https://wwww.itschools.co.za/projects"
},
{
"id":44315,
"name":"User Agents",
"image":{
"link":"http://www.zerohedge.com/sites/default/files/pictures/picture5781.jpg"
},
"groups":[
{
"id":191599,
"name":"Alchemy",
"url":"https://wwww.itschools.co.za/tools/alchemy"
},
{
"id":86822,
"name":"Empathy",
"url":"https://wwww.itschools.co.za/tools/empathy"
},
{
"id":86297,
"name":"Epiphany",
"url":"https://wwww.itschools.co.za/tools/epiphany"
},
{
"id":131837,
"name":"Harmony",
"url":"https://wwww.itschools.co.za/tools/hamony"
},
{
"id":174338,
"name":"Zagreb",
"url":"https://wwww.itschools.co.za/tools/zagreb"
}
],
"url":"https://wwww.itschools.co.za/tools"
}
];
return {
infos: function() {
return $q.resolve(infos);
}
}
}])
.controller('mainCtrl', ['$scope', 'dataService',
function($scope, dataService) {
dataService.infos().then(function(infos) {
$scope.infos = infos;
});
$scope.addGroup = function(groups) {
var group = {name: "This is a new group"};
groups.push(group);
};
}])
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
<div ng-app="app">
<div ng-controller="mainCtrl">
<!-- filter and highlight stuff removed for simplicity -->
<ul ng-repeat = "info in infos">
<img src="{{info.image.link}}"/> {{info.name}}
<li ng-repeat="group in info.groups">
<a ng-href="{{group.url}}">{{group.name}}</a>
</li>
<div class="add list">
+Add group
</div>
</ul>
</div>
</div>
The dataService is mocked up since it wasn't provided in the question, but it should be clear on how to transform that into something that could fetch the contents via e.g. the $http service.
One other change was to use ng-href="{{group.url}}" on your per-group <a>s; it wasn't mentioned but I assumed that's what the url member was for.
Try this
app.controller('mainCtrl', function($scope , dataService){
$scope.addGroup = function () {
$scope.infos = [];
var group = {name: "This is a new group"};
$scope.infos.push(group);
};

Filtering complex object inside nested ng-repeat

I want to filter object inside nested ng-repeat.
HTML:
<div ng-controller="MyController">
<input type="text" ng-model="selectedCityId" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
Controller:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (location.city_id === parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.item = function (detail) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (detail.pin == parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Here's the fiddle:
http://jsfiddle.net/suCWn/210/
I want to use multiple filter inside ng-repeat.
Example: Whenever user enters the ID in the input box. The list should filter based on cityID or PinCode.
if user enter '129818' it should show pin code result of 129818 along with its parent cityID
Similarly, if a user enter 400, the list should filter and show cityID result with 400 along with its child pin code.
EDIT:
Update Code http://codepen.io/chiragshah_mb/pen/aZorMe?editors=1010]
First, you must not filter locations with matching details. Use something like this in the search filter:
$scope.search = function (location) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || location.city_id === id ||
location.details.some(function(d) { return d.pin === id });
};
To show details if filtered by cityID, you have to find the parent location and check if it was filtered.
$scope.item = function (detail) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || detail.pin === id || locationMatches(detail, id);
};
function locationMatches(detail, id) {
var location = locationByDetail(detail);
return location && location.city_id === id;
}
function locationByDetail(detail) {
var shops = $scope.shops;
for(var iS = 0, eS = shops.length; iS != eS; iS++) {
for(var iL = 0, eL = shops[iS].locations.length; iL != eL; iL++) {
if (shops[iS].locations[iL].details.indexOf(detail) >= 0) {
return shops[iS].locations[iL];
}
}
}
}
EDIT Another, more flexible solution would be to remove all the filters from ngRepeats and do the filtering in a method that you call on ngChange of the search text. Here is the basic structure for this approach.
myApp.controller('MyController', function($scope, $http) {
var defaultMenu = [];
$scope.currentMenu = [];
$scope.searchText = '';
$http.get(/*...*/).then(function (menu) { defaultMenu = menu; } );
$scope.onSearch = function() {
if (!$scope.searchText) {
$scope.currentMenu = defaultMenu ;
}
else {
// do your special filter logic here...
}
};
});
And the template:
<input type="text" ng-model="searchText" ng-change="onSearch()" />
<ul>
<li ng-repeat="category in currentMenu">
...
</li>
</ul>
I have updated your filters. The problem is in your search filter you are only checking for the city_id, what you should do is:
Check if the typed id is city_id
Check if typed id is a pid of a child detail of given location
Similar thing for the item filter:
Check if the typed id is a pid of the detail being filtered
Check if the typed id is a city_id of the parent location of the detail passed in
Here is a working jsFiddle. I hope this helps.
By simply modifying the JSON to include the city_id for children so you don't need to loop through it to get the parent's city_id, the solution is as easy as this:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if (!$scope.selectedCityId)
return true;
//if user's input is contained within a city's id
if (location.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
for (var i = 0; i < location.details.length; i++)
//if user's input is contained within a city's pin
if (location.details[i].pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
$scope.item = function (detail) {
if (!$scope.selectedCityId)
return true;
//if user's input is contained within a city's id
if (detail.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
//if user's input is contained within a city's pin
if (detail.pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
Modified JSON
$scope.shops=[{"category_id":2,"locations":[{"city_id":368,"details":[{"city_id":368,"pin":627718,"state":'MH'}]}]},{"name":"xxx","category_id":1,"locations":[{"city_id":400,"region_id":4,"details":[{"city_id":400,"pin":627009,"state":'MH'},{"city_id":400,"pin":129818,"state":'QA'}]},]},];});
If directly modifying the JSON is not possible, you can modify it like this in this controller directly after this $scope.shops = ...json... statement:
for(var i=0; i<$scope.shops.length; i++)
for(var j=0, cat=$scope.shops[i]; j<cat.locations.length; j++)
for(var k=0, loc=cat.locations[j]; k<loc.details.length; k++)
loc.details[k].city_id=loc.city_id;
Working fiddle:
http://jsfiddle.net/87e314a0/
I tried to make the solution easier to understand :
index.html :
<div ng-controller="MyController">
<input type="text" ng-model="search.city_id" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search.city_id" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
</div>
app.js :
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Here's the fiddle :
mySolution

Add item to array Angular

I have a table with these fields: product, lot, input1, input2. You can clone a line, and you can add a new line.
What I want to do is that for each row you can add a new Lot created by a "number" and by "id" that user write in the input field under the Select lot. And I wanted that the script add the new Lot in the json data and the lot 's option list.
This is the function for add that I tried to do:
$scope.addLot = function() {
var inWhichProduct = row.selectedProduct;
var newArray = {
"number": row.newLot.value,
"id": row.newLot.id
};
for (var i = 0; i < $scope.items.length; i++) {
if ($scope.items[i].selectedProduct === inWhichProduct) {
$scope.items[i].selectedLot.push(newArray);
}
}
};
-->> THIS <<-- is the full code.
Can you help me?
I think your question is a little too broad to answer on Stack Overflow, but here's an attempt:
<div ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="lot in lots">
<td>{{ lot.id }}</td>
<td>{{ lot.name }}</td>
</tr>
</table>
<p>name:</p> <input type="text" ng-model="inputName">
<p>id:</p> <input type="text" ng-model="inputId">
<button ng-click="addLotButton(inputId, inputName)">Add</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.lots = [{
name: "test",
id: 1
},
{
name: "test2",
id: 2
}
];
$scope.addLot = function(lotId, lotName) {
var newLotObject = {
name: lotName,
id: lotId
};
$scope.lots.push(newLotObject);
};
$scope.addLotButton = function(id, name) {
$scope.addLot(id, name);
};
$scope.addLot(3, "Another test");
});
</script>
Basically this code just takes some input and adds an object to the scope for that input. The table is created using an ng-repeat of this data. It's not great code at all but it's just a quick example.
The push method adds newArray to selectedLot array. It's not working on the JSON data but on arrays. If you want to have the JSON, you can give a try to :
var myJsonString = JSON.stringify(yourArray);
It will create a JSON string based on the parameter
Maybe you should try to structure your data to make lots as properties of products.
{
products: [
{id: 1, lots: [{id:1}, {id:2}]},
{id: 2, lots: [{id:1}, {id:2}]}
]
}
To add a lot to a product :
product = products[0];
product.lots.push(newArray);
Change the fallowing:
html:
<button ng-click="addLot(row.selectedProduct.id,row.newLot.value,row.newLot.id)">Add</button>
js:
$scope.addLot = function(id,val,lotId) {
// console.log(id);
var inWhichProduct = id;
var newArray = { "value": val, "id": lotId };
//console.log($scope.items)
angular.forEach($scope.items,function(v,i){
if($scope.items[i].id == id )
{
$scope.items[i].lots.push(newArray);
console.log($scope.items[i].lots);
}
});
};
http://plnkr.co/edit/W8eche8eIEUuDBsRpLse?p=preview

Categories

Resources