Angular.js Select option without using ng-option directive - javascript

I get an json oject from a service, and I use some of it's fields to populate my select option list.
When I try to print the selected value in my controller, output response is "undefined".
Where am I wrong?
JSON
[ {
"Accreditment" : {
"Id" : "1",
"Creator" : "John Smith",
"IdCreator" : "1",
"CreationDate" : "2014-07-01T18:13:51+02:00",
"CostCenter" : [ "5411-Channel1", "5412-Channel2" ],
"Destination" : [ "Playout Channel1", "Playout Channel2" ],
"IdUserEnabled" : [ "1", "2" ],
"WorkOrderType" : [ "New Asset", "Subtitling" ],
"StartDate" : "2013-05-04T18:13:51+02:00",
"EndDate" : "2014-10-04T18:13:51+02:00",
"Status" : "enabled"
}
} ]
HTML
<select class="form-control" ng-model="myOption" ng-change="selectAction()">
<option ng-repeat="cost in work.Accreditment.CostCenter" value="{{cost}}">{{cost}}</option>
</select>
CONTROLLER
mwm3.controller('CreateWorkOrderCtrl',function($scope){
$scope.selectAction=function(){
console.log($scope.myOption);
};
});

The issue is with your JSON.
Just remove the array of the JSON. It will work Fine.
Read more about JSON
JSON is an object not an array!
correction:
$scope.work = {
"Accreditment" : {
"Id" : "1",
"Creator" : "John Smith",
"IdCreator" : "1",
"CreationDate" : "2014-07-01T18:13:51+02:00",
"CostCenter" : [ "5411-Channel1", "5412-Channel2" ],
"Destination" : [ "Playout Channel1", "Playout Channel2" ],
"IdUserEnabled" : [ "1", "2" ],
"WorkOrderType" : [ "New Asset", "Subtitling" ],
"StartDate" : "2013-05-04T18:13:51+02:00",
"EndDate" : "2014-10-04T18:13:51+02:00",
"Status" : "enabled"
}
}

I have added ng-selected. Try this out.
<select class="form-control" ng-model="myOption" ng-change="selectAction()">
<option ng-repeat="cost in work.Accreditment.CostCenter" value="{{cost}}"
ng-selected="cost==myOption">
{{cost}}
</option>
</select>
Hope this helps.....

As I see from your tags, you're using angularjs. Angular has its own directive for the select tag. It goes something like this:
<select ng-model="myCost" ng-options="cost in work.Accreditment.CostCenter">
<option value="">-- choose cost --</option>
</select>
And, yes, remove the array brackets from your json. You're traversing an object in this case. No need for an array.

Why don't you just do it like this?
<select ng-model="selectedItem" ng-options="item as item.Accreditment.Creator for item in list"></select>

Related

array in array filter - javascript

hello i need help with array , as you can see my data
{
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
I can access elements such as id , title or logo because they are not arrays.
How can I loop through the data inside the array since there is an array in the category in yield?
var data = this.database.filter((item) => item.type == searchType)
var data = this.database.filter((item) => item.category == searchCategory)
It's okay because my type value doesn't have an array.
But when I enter my category value, it only gets the first index[0]. It does not look at other indexes.
in summary,
item.category[0] , item.category[1] , item.category[2]...........
How can I get index browsing like
if your data looks like this :
let data ={
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
and if we have array of data you can do something like this :
myArray.filter(item=>item.category.indexOf(searchCategory)>=0)
but if you want to explore in object rather than array you can do this :
data.category.indexOf(searchCategory)>=0
You could make this a bit generic, by testing whether the targeted field is an array, using Array.isArray, and then call a filter on each element, and see if any is positive (using .some()). The filter can be function that is provided, so that it can perform a simple match, or apply a regular expression, or anything else.
Instead of testing with Array.isArray you could skip that step and check whether the value has a .some() method. If so, calling it will give the desired outcome, and otherwise (using the .? and ?? operators), the filter should be applied to the value as a whole:
Here is how that looks:
function applyFilter(data, field, filter) {
return data.filter(item => item[field]?.some(filter) ?? filter(item));
}
// Example use:
var data = [{
"category" : [ "Action", "Thriller", "Horror"],
"type" : "Series",
}, {
"category" : [ "Historical", "Romance" ],
"type" : "Theatre",
}];
// Find entries that have a category that looks like "roman*":
var result = applyFilter(data, "category", value => /^roman.*/i.test(value));
console.log(result);
If you are running on an older version of JavaScript, and don't have support for .? or ??, then use:
return data.filter(item => Array.isArray(item[field])
? item[field].some(filter)
: filter(item));

AngularJS select not populating dynamically

I have the following JSON (test JSON as how it comes from the server):
$scope.allCategoriesAndSubcategories = {
"category" : {
"categoryname" : "pasteleria",
"subcategory" : [
{"subcategoryname" : "pastel tradicional", "subcategoryid" : "1"},
{"subcategoryname" : "pastel con fondant", "subcategoryid" : "2"}
]
},
"category" : {
"categoryname" : "eventos",
"subcategory" : [
{"subcategoryname" : "boda", "subcategoryid" : "1"},
{"subcategoryname" : "cumpleanos", "subcategoryid" : "2"}
]
}
};
Then on the select in the HTML I do the following:
<div input-field>
<select material-select
ng-model="picture.category1" required>
<optgroup ng-repeat="category in allCategoriesAndSubcategories" label="{{category.categoryname}}">
<option value="{{category.subcategory.subcategoryid}}">{{category.subcategory.subcategoryname}}</option>
</optgroup>
</select>
<label>Categoría #2</label>
</div>
When I console.log() I get the actual object so it's not undefined, however the select is not populating. Should I do something else to populate it? I'm new to angularJS and I can't find an example similar to this one
The HTML is invalid if you wish to create list of options
<div input-field>
<select material-select ng-model="picture.category1" required>
<optgroup ng-repeat="category in allCategoriesAndSubcategories" label="{{category.categoryname}}">
<option ng-repeat="subcategory in category.subcategory" value="{{subcategory.subcategoryid}}">{{subcategory.subcategoryname}}</option>
</optgroup>
</select>
<label>Categoría #2</label>
</div>
then after you select element the model picture.category1 should be populated
working plunker http://codepen.io/maurycyg/pen/PZpRRy
also your data should be formatted differently
$scope.allCategoriesAndSubcategories = [{
"categoryname": "pasteleria",
"subcategory": [{
"subcategoryname": "pastel tradicional",
"subcategoryid": "1"
}, {
"subcategoryname": "pastel con fondant",
"subcategoryid": "2"
}]
}, {
"categoryname": "eventos",
"subcategory": [{
"subcategoryname": "boda",
"subcategoryid": "1"
}, {
"subcategoryname": "cumpleanos",
"subcategoryid": "2"
}]
}];
});
I think that proble is here
<option value="{{category.subcategory.subcategoryid}}">
Subcategory is array, and i think that you should use new ng-repeat to make list of <option> tags

How to show JSON as formatted view in html

I need to view JSON in my html page as formatted view. JSON come from database. I need to show it nut in Formatted view.
Just like
{
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}]
}
Anyone have any idea or suggestion ? or any resource that may help.
Edited: I want to create a JSON parser. User input different json and can view in formatted view.
Try JSON.stringify(data), its a Javascript function. Hope it might help.
Refer: Detail Explaination
If you are using PHP then use json_encode
Refer: json_encode manual
Since your are using angular-js, you can simply load your JSON feed from your controller then use the ng-repeat function to iterate over the items into your view page. Here down a sample where of how your HTML view can look like and you may need to style and build the blocks as per your needs:
<span>items:</span>
<span>[</span>
<br/>
<div class="item" ng-repeat="item in items">
<span>{</span><br/>
<span class="field">year : {{item.year}}</span><br/>
<span class="field">boat : {{item.boat}}</span><br/>
<span class="field">position : {{item.position}}</span><br/>
<span>}</span>
</div>
You can find a working sample in this JSFiddle.
First: your remote JSON is invalid: it's missing an ending bracket for crews.
It should be like this:
{
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}] // Missing this bracket
}
You didn't mention if your JSON is remote or not. I'm assuming not, so I'll use a local JavaScript var with eval function in this sample code.
<script type="text/javascript">
var content = {
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}]
};
var json = eval(content);
for (c in json.crews) {
var crew = json.crews[c];
for (i in crew.items) {
var item = crew.items[i];
console.log(item.year);
console.log(item.boat);
console.log(item.position);
console.log(item.name);
}
}
</script>
I'm using console.log to output, so you'll be able to see data only if you open the browser console:

MongoDB return specific fields from array

I want to limit my query's result to a set of fields. This is one of my documents:
{
"_id" : "WA9QRuiWtGsr4amtT",
"status" : 3,
"data" : [
{
"name" : "0",
"value" : "Text ..."
},
{
"name" : "1",
"value" : "12345678"
},
{
"name" : "2",
"value" : "Text"
},
{
"name" : "4",
"value" : "2"
},
{
"name" : "8",
"value" : true
},
{
"name" : "26",
"value" : true
},
],
"userId" : "7ouEumtudgC2HX4fF",
"updatedAt" : NumberLong(1415903962863)
}
I want to limit the output to the status field as well a the first and third data document.
This is what I tried:
Meteor.publish('cases', function () {
var fields = {
currentStatus: 1,
'data.0': 1,
'data.2': 1
};
return Cases.find({}, { fields: fields });
});
Sadly it doesn't work. Something else I found is $elemMatch but it only returns the first element:
data: {
$elemMatch: {
name: {
$in: ['0', '2']
}
}
},
How can I limit the output to these fields?
To display status and data(unlimited) fields try
cases.find({}, {"status":1, "data":1})
This is simple query, to limit "data" output you will need to work harder :)
Get 1 element by data.name (not by position):
cases.find({}, {status:1, "data": {$elemMatch:{name:"0"}}})
Get 1 element by data.name, but from a list of values:
cases.find({}, {status:1, "data": {$elemMatch:{name:{$in:["0", "1"]}}}})
To get close to your question, you may try redact. That is new in Mongodb 2.6.
Or play with $unwind and .aggregate() in previous editions.
So far, I do not see a way to return array elements based on a position.

java.lang.ClassCastException calling RedQueryBuilderFactory.create with args

This line in my JS file:
RedQueryBuilderFactory.create(config,
'SELECT "x0"."title", "x0"."priority" FROM "ticket" "x0" WHERE ("x0"."status" = (?))',
[]
);
works fine witih an empty array as the 3rd parameter. This parameter is supposed to be an array of strings according to the documentation and any sample code I can find. When I pass a string in the array it fails:
RedQueryBuilderFactory.create(config,
'SELECT "x0"."title", "x0"."priority" FROM "ticket" "x0" WHERE ("x0"."status" = (?))',
['in_process']
);
I get java.lang.ClassCastException in the Safari console. Here's the related part of the config if it's relevant:
var config = {
meta : {
tables : [ {
"name" : "ticket",
"label" : "Ticket",
"columns" : [ {
"name" : "title",
"label" : "Title",
"type" : "STRING",
"size" : 255
}, {
"name" : "priority",
"label" : "Priority",
"type" : "REF"
} ],
fks : []
} ],
types : [ {
"name" : "REF",
"editor" : "SELECT",
"operators" : [ {
"name" : "IN",
"label" : "any of",
"cardinality" : "MULTI"
}]
} ]
}
};
Looks like this is a bug in passing in parameter values. Internally it is expecting a collection but this is not happening.
Best if you raise a https://github.com/salk31/RedQueryBuilder bug report here?
NB Should be "IN" not "="

Categories

Resources