handling json response Array - angularjs

I have a json response as given below from backend
JSON:
{
"json": {
"response": {
"servicetype": "1",
"functiontype": "10011",
"statuscode": "0",
"statusmessage": "Success",
"data":{
"roleid": 36,
"rolename": "Product Managers",
"divisionlabel": "Department ",
"subdivisionlabel": "Category",
"roleinformation": {
"QA": [
{
"White Box Testing": 10
}
]
}
},
{
"roleid": 38,
"rolename": "Managers",
"divisionlabel": "Department ",
"subdivisionlabel": "Category",
"roleinformation": {
"QA": [
{
"Black Box Testing": 10
}
]
}
}
}
}
}
}
I have inserted my role names in a dropdown $scope.model.rolename .
If my rolename is selected as product managers I want to give value of my $scope.maxcount value as "White Box Testing": 10 .It should be dynamic , based on selection the value will change. Now in dropdown if I select Manager the $scoope.maxcount for manager value will change. I have done till dropdown , dont know to handle after it .
JS:
` `UserService.getAssignRoles(json).then(function(response) {
if (response.json.response.statuscode == 0 && response.json.response.statusmessage == 'Success')
{
$scope.model.roles= [], assignrolesArray = [];
assignrolesArray = unasresdata.concat(assresdata);
$scope.model.assignroles = assignrolesArray;
}
});
HTML:
<select class="form-control" name="role"
ng-model="model.rolename"
ng-change="getassignRole(model.rolename)">
<option selected>Select Roles</option>
<option ng-repeat="role in model.assignroles track by $index"
value="{{role.rolename}}">{{role.rolename}}</option>
</select>
<input type = "text" ng-model=$scope.maxcount>

You can pass your model.assignroles and scope value into this getassignRole() function and from that, you can get property and set it to your scope variable.
Do install lodash library and inject it.
HTML
ng-change="getassignRole(model.assignroles, model)"
JS
$scope.getassignRole= function(model.assignroles, rolename){
console.log(model.assignroles);
var test = _.filter(model.assignroles, function(o){
return o.rolename === rolename;
})
console.log(rolename);
console.log(test[0].roleinformation);
};
Sample jsfiddle: https://jsfiddle.net/alpeshprajapati/5kpxzrgf/1/
You can access required property then.
Hope it helps.

Related

Angular js filter for JSON key/value nested object is not working for me

My JSON data looks like the below code. Can you any one please help me to filter data by code/desc which is in the state property.
$scope.agent =
{
"0d297c1711de":
[{
"applicationName": "rewards-accounts", "agentId": "0d297c1711de",
"status": { "agentId": "0d297c1711de", "eventTimestamp": 1510580172247, "state": { "code": 100, "desc": "Running" } }
}],
"16f279d66923":
[{
"applicationName": "rewards-accounts-details", "agentId": "16f279d66923",
"status": { "agentId": "0d297c1711de", "eventTimestamp": 1510580172247, "state": { "code": 201, "desc": "Unexpected Shutdown" } }
}],
"203b353d32ef":
[{
"applicationName": "rewards-accounts-details", "agentId": "203b353d32ef",
"status": { "agentId": "0d297c1711de", "eventTimestamp": 1510580172247, "state": { "code": 200, "desc": "Shutdown" } }
}]
};
I have used this filter in ng-repeat . It is not working. selectedCode is my model data to be filtered.
| filter:{status:{ state: { code: **selectedCode**}}}
As stated in this SO
You need to pass in the argument to filter by, which in your particular case looks like:
ng-repeat="a in agent | filter: {status: {state: {code: filter.key}}}"
With thanks to #Ray
JSFiddle here for further reference.
Hope it helps.
You can use a custom filter to filter your nested data,
in your controller create your filter
$scope.customFilter = function (row) {
var result = false;
if($scope.filter == undefined || $scope.filter == ""){
result = true;
}
else{
angular.forEach(row, function(value, key){
if(value.state != undefined){
if(value.state.code == $scope.filter)
result = true;
}
});
}
return result;
};
and add this filter to your ng-repeat
<div ng-repeat="item in agent">
<div ng-repeat="x in item | filter:customFilter">
{{x}}
</div>
</div>
Demo

angular predicate filter not returning element

I'm trying to use a predicate function to filter some items because the object structure might be a little too deep for straight template filtering. I have an array of items that I'm tring to filter based on user selected region and user selected country. When I filter the items in the template with the selected region the correct items are rendered. However, I need to filter deeper i.e., the user selects countries of the selected region. The predicate function appears to be filtering the items correctly i.e., printing to console, but the items are not rendering in the template.
{
"id": 2,
"name": "my test app",
"version": "1.0.0",
"regions": [
{
"id": 11,
"name": "LATIN_AMERICA",
"timeZone": "UTC+8",
"selected": true,
"countries": [
{
"id": 47,
"name": "Brazil",
"timeZone": "UTC+08:00",
"isoCode": "BR",
"selected": false
},
{
"id": 46,
"name": "Argentina",
"timeZone": "UTC+08:00",
"isoCode": "AR",
"selected": true
}
]
}
]
},
{
"id": 2,
"name": "my test app",
"version": "1.0.1",
"regions": [
{
"id": 11,
"name": "LATIN_AMERICA",
"timeZone": "UTC+8",
"selected": true,
"countries": [
{
"id": 47,
"name": "Brazil",
"timeZone": "UTC+08:00",
"isoCode": "BR",
"selected": true
},
{
"id": 46,
"name": "Argentina",
"timeZone": "UTC+08:00",
"isoCode": "AR",
"selected": false
}
]
}
]
}
function filterByRegionCountry(app) {
if(vm.selectedCountry !== undefined) {
angular.forEach(app.regions, function(appRegion, i) {
angular.forEach(appRegion.countries, function(appCountry, j) {
angular.forEach(vm.selectedCountry, function(selectedCountry, k) {
if((appCountry.name == selectedCountry.name) && appCountry.selected) {
console.log(app);
return true;
}
});
});
});
}
}
<select class="form-control" ng-model="vm.selectedRegion" ng-options="region.name for region in vm.filterRegions">
<option value="">--select region--</option>
</select>
<select class="form-control" ng-model="vm.selectedCountry" ng-options="country.name for country in vm.selectedRegion.countries" multiple>
<option value="">-- select country --</option>
</select>
<tr ng-repeat="app in vm.appVersions | filter:vm.filterByRegionCountry">
<td>
<label>{{ app.name }}</label>
</td>
<td>
<label>{{ app.version }}</label>
</td>
</tr>
// EDIT
Using .some (see answer below) or for loops with a break fixes the issue.
if(vm.selectedCountry !== undefined) {
for(var i = 0; i < app.regions.length; i++) {
for(var j = 0; j < app.regions[i].countries.length; j++) {
for(var k = 0; k < vm.selectedCountry.length; k++) {
if((app.regions[i].countries[j].name == vm.selectedCountry[k].name) && app.regions[i].countries[j].selected) {
console.log(app);
return true;
break;
}
}
}
}
}
Filter need either true or false to exevalue.
You are using angular forEach and there no break for forEach
Try javascript .some instead
like this
if (vm.selectedCountry) {
return app.regions.some(function (appRegion) {
return appRegion.countries.some(function (appCountry) {
return vm.selectedCountry.some(function (selectedCountry) {
if ((appCountry.name == selectedCountry.name) && appCountry.selected) {
console.log(app);
return true;
}
});
});
});
}
else
return false;

How fill dropdown menu

I´m working with bootstrap and angularjs for the user interface and google appengine with java as a backend.
Just now I have a problem filling a dropdown menu, I see an empty list so I suspect that the problem is in the html code.
Front end:
<div class="dropdown" >
<select id="mySelPartido" class="form-control">
<option ng-repeat="partido in data.locations.partidos"
ng-selected="partido.selected" ng-model="partido.partido">{{partido.partido}}</option>
</select>
</div>
js in angular code (I debug this code and it works!):
$scope.status = 'loading...';
$scope.partido = "Select partidos";
$scope.data = {
"locations": {}
};
$http.get('https://myservice.appspot.com/_ah/api/partidoendpoint/v1/partido')
.then(function (res) {
$scope.data.locations.partidos = res.data.items;
$scope.status = "loaded "
+ $scope.data.locations.partidos.length
+ " partidos.";
});
My service response from app engine backend:
{
"items": [
{
"id": {
"kind": "Partido",
"appId": "s~myservice",
"id": "5066549580791808",
"parent": {
"kind": "Provincia",
"appId": "s~myservice",
"id": "5086253011697664",
"complete": true
},
"complete": true
},
"name": "Florencio Varela",
"kind": "partidoendpoint#resourcesItem"
},
{
"id": {
"kind": "Partido",
"appId": "s~myservice",
"id": "5094432508477440",
"parent": {
"kind": "Provincia",
"appId": "s~myservice",
"id": "5086253011697664",
"complete": true
},
"complete": true
},
"name": "La Matanza",
"kind": "partidoendpoint#resourcesItem"
}
],
"kind": "partidoendpoint#resources",
"etag": "\"PQS12KaO4-dKVfv_BcCoEkbIN9g/GvZKzZUnrHEP8TKWybTkd_fJbnc\""
}
Check the angular documentation for select.
Maybe try use the ngOptions directive in the select element. Example :
function demo($scope) {
$scope.items = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'baz' }
];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="demo">
<select ng-options="item.name for item in items"
ng-model="selected">
</select>
<p>You have selected : {{ selected }}
</div>

Angular JS Order By Filter not working for dynamic predicates

I am creating a Grid Control in Angular JS. ( I don't want to use ng-grid, smart table, etc for some reason)
Plunkr URL : http://plnkr.co/edit/arkCZcfXTIsW7sFCxisn?p=preview
On top of the table generated, i have populated fields in the combobox so that user is allowed to search on specific columns
or as free search.
As I see From here :
https://docs.angularjs.org/api/ng/filter/filter
For free search, I have used the syntax as {$:Value} and for column based search, {ColName:Value} syntax
However, I am unable to get it to work when I bind the column names to combobox.
I do get static search to work Eg if I write {'Code':"1"}, this works. but if I take "Code" from a combobox, it doesnt work.
Need help on setting dynamic filter.
This one also does not seem to help.
angular filter with dynamic list of attributes to search
This is the HTML
<div ng-controller="MyGrid">
Search in Column
<select ng-model="FilterByColumn" >
<option value="$">All</option>
<option ng-repeat="hdr in headers | orderBy : hdr.displayOrder" ng-show="hdr.isVisible" value="{{hdr.name}}" >
{{hdr.caption}}
</option>
</select>
Value : <input type="text" ng-model="searchKeyword" />
<br />
Remove Sort
<table>
<thead>
<tr>
<th ng-repeat="hdr in headers | orderBy : hdr.displayOrder" ng-show="hdr.isVisible">
{{hdr.caption}}
</th>
</tr>
</thead>
<tbody>
<%--<tr ng-repeat="dataVal in data | filter: {FilterByColumn : searchKeyword} | orderBy:predicate:reverse "> **Does not work--%>**
<%--<tr ng-repeat="dataVal in data | filter: {$ : searchKeyword} | orderBy:predicate:reverse "> **This works--%>**
<tr ng-repeat="dataVal in data | filter: GetFilter (FilterByColumn, searchKeyword) | orderBy:predicate:reverse "> **<!-- Does not work -->**
<td ng-repeat="hdr in headers | orderBy : hdr.displayOrder" ng-show="hdr.isVisible">
{{dataVal[hdr.name]}}
</td>
</tr>
</tbody>
</table>
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}} ; SearchBy = {{FilterByColumn}} ; Search Key : {{searchKeyword}} </pre>
</div>
This is the JS :
'use strict';
var MyApp = angular.module('MyApp', []);
MyApp.controller('MyGrid', function ($scope) {
$scope.predicate = 'Code';
$scope.reverse = false;
$scope.FilterByColumn = '$';
$scope.headers = [
{
"name": "Code",
"caption": "Code",
"isVisible": true,
"displayOrder": 12
},
{
"name": "DispName",
"caption": "My Name",
"isVisible": true,
"displayOrder": 1
},
{
"name": "Locked",
"caption": "Islocked",
"isVisible": true,
"displayOrder": 2
}
];
$scope.data =
[{
"Code": "1",
"DispName": "abdul",
"Locked": "0"
},
{
"Code": "2",
"DispName": "Hemant",
"Locked": "0"
},
{
"Code": "3",
"DispName": "Rahul",
"Locked": "0"
},
{
"Code": "4",
"DispName": "Sandy",
"Locked": "0"
},
{
"Code": "5 ",
"DispName": "Nihal",
"Locked": "0"
},
{
"Code": "6",
"DispName": "Sachin",
"Locked": "0"
},
{
"Code": "7",
"DispName": "abdul f",
"Locked": "0"
},
{
"Code": "8",
"DispName": "abdul g",
"Locked": "0"
},
{
"Code": "9",
"DispName": "abdul h ",
"Locked": "0"
},
{
"Code": "10",
"DispName": "abdul i",
"Locked": "0"
}
];
$scope.getValue = function (obj, PropName) {
return obj[PropName];
};
$scope.SetSort = function (objName) {
//alert(objName);
$scope.predicate = objName;
$scope.reverse = !$scope.reverse;
};
$scope.GetFilter = function (srchCol, Srchval) {
//alert(srchCol);
//alert(Srchval);
if (srchCol == "") {
return { $: Srchval };
}
else {
return { srchCol: Srchval };
}
};
});
That is because when you write { srchCol: Srchval } - srcCol is the property name and is not substituted with the value in variable srcCol, try this syntax instead:
$scope.GetFilter = function (srchCol, Srchval) {
if (srchCol == "") {
return { $: Srchval };
}
else {
filter = {};
filter[srchCol] = Srchval;
return filter;
}
};

Get selected item with ng-options

I have an array with attributes and I'm trying to select a certain one on load.
Each of my attributes have attribute object, type object and an array of attributeValues.
I want to select the attribute value with chosen=true
Here's my Angular code:
app.controller('MainCtrl', function($scope) {
$scope.profileData = { "attributes": [{
"attribute": {
"id": 56,
"name": "Hárlitur",
"typeID": 5,
"visibleToUsers": true
},
"type": {
"id": 5,
"typeName": "list"
},
"attributeValues": [{
"id": 109,
"attributeID": 56,
"value": "Ljós",
"chosen": true
}, {
"id": 110,
"attributeID": 56,
"value": "Dökkur",
"chosen": false
}],
"valueText": null
}]};
$scope.changeValue = function changeValue(attribute, value) {
alert(JSON.stringify({"attributeID":attribute.attribute.id, "type": attribute.type.typeName, "value":value.id}));
};
});
Here's my HTML code:
<div ng-repeat="attribute in profileData.attributes">
<select ng-change="changeValue(attribute, attributeValue)" ng-options="item.id as item.value for item in attribute.attributeValues" ng-model="attributeValue.id"></select>
</div>
Here's my plunker:
http://plnkr.co/edit/VMbmSB?p=preview
I don't know if this is the best solution to your problem, but it works.
What I ddid was to simply create a function to search for the chosen value set as true. Upon finding that value I set the scope model as that attribute value. Then I called that function immediately afterwards.
$scope.selectChosen = function selectChosen() {
var attrVals = $scope.profileData.attributes[0].attributeValues;
for (var i = 0; i < attrVals.length; i++) {
if (attrVals[i].chosen) {
$scope.attributeValue = attrVals[i];
break;
}
}
};
$scope.selectChosen();
The complete plunker is at: http://plnkr.co/edit/UcmQ8Q?p=preview
I found a better Angular-ish solution:
<div ng-repeat="attribute in profileData.attributes">
<select ng-model="attributeValue" ng-change="changeValue(attribute, attributeValue)">
<option value="">Select</option>
<option ng-repeat="obj in attribute.attributeValues" value="{{obj.id}}" ng-selected="obj.chosen">{{obj.value}}</option>
</select>
</div>

Resources