ngOptions From Simple Key-Value Object - angularjs

There are other answers that deal with using ng-option with an object formatted like so:
$scope.opts = [
{value: 111, text: '1st' },
{value: 222, text: '2nd' }
];
My question is, can it be done with an object formatted like this?
$scope.opts = [
{'111': '1st'},
{'222': '2nd'}
];
Trying it out doesn't work for me.
Any help?
To clarify:
I'd like the options to be like this <option value="111">1st</option, etc, where the browser shows 1st, and the model returns 111. Can this be done with an array of simplified objects?

No, the answer you point out does not say the same thing as you case. You have an array of objects having a single property with different names; the name of the single property is the key, the value is tha value.
The "object" syntax for the select is about an object, i.e. in your case it should be:
$scope.opts = {
'111': '1st',
'222': '2nd'
};
What you lose with this? No guaranteed iteration order.

Related

create array for morris js in laravel

I have difficulty loading certain data from the table to get a json array and include it into the morris js donut (example: https://codepen.io/ncarlucci/pen/JYxQBK)
I want to load from the table subscriber the different names from the column type and count them to get the following array:
[
{value: 50, label: 'typename1'},
{value: 25, label: 'typename2'},
{value: 25, label: 'typename3'},
],
if I do it like this:
$subscriber = Subscribe::select('type')->get()->groupBy('type')
->map(function($subscribe){
return $subscribe->count();
})->toJson();
I get the follow output, but it is false:
{"company":1,"person":16,"user":6}
There might be a nicer way to handle your case, but since you didn't provide more informations about your model or database structure, this should work:
$subscriber = Subscribe::select('type')->get()
->groupBy('type')
->map(function($subscribe, $label) {
return ['value' => $subscribe->count(), 'label' => $label];
})
->values()
->toJson();
The key is to build the inner array element within the map function, then call values() to get rid of the unneded outer label left by the map function.
If you need further explaination, just ask in the comments below

AngularJS how to have multiple $filter in a controller?

The leftValue array contains JSON information such as { name: 'John', gender: 'male' }
I am trying to filter information by both name and gender in a search bar. For now, the filter only filtered by name. How can I filter by both name and gender?
scope.leftValue = $filter('filter')( leftValue, {
'name': text
})
What I have tried
scope.leftValue = $filter('filter')( leftValue, {
'name': text,
'gender': text,
})
I think your getting a little mixed up. You can specify an object map like your second example. This is what the docs state about it when you do.
Object: A pattern object can be used to filter specific properties on
objects contained by array. For example {name:"M", phone:"1"}
predicate will return an array of items which have property name
containing "M" and property phone containing "1". A special property
name $ can be used (as in {$:"text"}) to accept a match against any
property of the object or its nested object properties. That's
equivalent to the simple substring match with a string as described
above. The predicate can be negated by prefixing the string with !.
For example {name: "!M"} predicate will return an array of items which
have property name not containing "M".
The important thing to take away here is the second sentence and the and. Meaning in order for a match the string, in your case text, has to match ALL properties specified in your map.
Searching for just male wont match if the name is only John for example. But searching for ma would return the following record:
{
name: 'mark',
gender: 'male'
}
Just for FYI you can also search by object map through the view but it has the same limitations.
That being said it is possible to use the $ wildcard giving it a comma separated list of properties. This will do an or match over any of the properties.
{
$: 'name,gender'
}
The catch here is all properties will have the same value checked against them.
Here's a fiddle showing them in action.
The other answers sum up quite well the alternatives, just felt they were lacking in explaining what was happening and the reasons behind it.
You can use chain of filters.
var result1 = $filter('filter')( leftValue, {'name': text })
var result2 = $filter('filter')( result1 , {'gender': text })
i appreciate you said in the controller, but just to give you options you can have it all done in your HTML.
{{yourJSONLinkedToScope | filter: name | filter: gender}}
where name and gender are ng-models from the input boxes.
I think better we do it in html.
<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">
$scope.ageFilter = function (player) {
return (player.age > $scope.min_age && player.age < $scope.max_age);
}
You can check the way they do in this link:
AngularJS multiple filter with custom filter function

Joining a series of arrays into one 'parent' array (AngularJS)

I have a series of arrays, filled with objects - in JSON format. They look something like this:
Group 1
[
{ "name" : "John",
"age" : "31"
},
{ "name" : "Bob",
"age" : "33"
}
]
Group 2
[
{ "name" : "Jim",
"age" : "46"
},
{ "name" : "Harry",
"age" : "23"
}
] // ... and so on ...
In Angular, how can I join the two arrays to form an array of arrays? I'm guessing it's group1.concat(group2), or something like that? I'm not sure where to do it though, would I do this in the controller?
Currently I have a $scope property assigned to each variable, would I make a new $scope property that was a concatenated array of each of these?
And would that be something like:
$scope.allGroups = []
$scope.allGroups = $scope.group1.concat($scope.group2)
// since 'allGroups', 'group1', and 'group2' have all been defined can I do...
allGroups = group1.concat(group2) // ...or does $scope need to be used each time?
My intention is (with the necessary filters) to be able to do an ng-repeat through all groups as they will now all be linked to one $scope variable.
I'm pretty sure that's laiden with errors, but I thought it better to provide some bad code than nothing at all, just so it was more evident what I was trying to do. If there are better approaches (which I'm sure there are), I'm all ears.
Thanks in advance
You're right, array1.concat(array2) is the good method to use.
Now the question is, do you need group1 and group2 to be on your $scope ? Do you need to display them ?
If the answer is no, then you could simply do as follow:
Recover the two arrays and store them in 2 "private" variables
Concat them into a variable set into your $scope
You dont have to set variable into your $scope if you dont display them. It will then look like this:
$scope.allGroups = group1.concat(group2)
Otherwise, no other choice than do like you said:
$scope.allGroups = $scope.group1.concat($scope.group2)
EDIT
If you want an array containing the group1 and group2 arrays, and not only their content, you can simply use the push() method as follow:
$scope.allGroups = [];
$scope.allGroups.push(group1, group2);
If you want to be able to access the concatenated array from your views you have to attach the concatenated array in the $scope object, so you will have to use
$scope.allGroups = $scope.group1.concat($scope.group2)
In the case that you leave var allGroups not attached to the $scope object allGroups will be a local variable to the controller function and will be available only through a closure
You can use concat() to join one array with another.
concat() function returns an array.
Here is the code:
$scope.a = [1,2];
$scope.b = [3,4];
$scope.c = $scope.a.concat($scope.b);

AngularJS insert data in nested array and sorting with a specific nested array object

I'm a newbie in AngularJS and I want to have a JSON-like nested array in my $scope.tabledata. But everytime I click the add button, nothing happens :( Your ideas will be highly appreciated.
Here's my plunker:
http://plnkr.co/edit/GdoaYI
//Array I want to Achieve
var SampleDataToProduce = {
"Continent":"Asia",
"ContinentId":"ContId1",
"Countries": {
"Japan":
[
{
"Id": 3,
"ColumnIndex": 3,
"ColumnName":"Tokyo",
"Interests":{
"Music":["JRock","JPop"]
}
},
{
"Id": 4,
"ColumnIndex":2,
"DisplayText":"Comment",
"ColumnName": "Osaka",
"Interests":"Music","Anime":{}
}
]
}
}
You have quite a few syntax errors in your scripts. I would suggest you check your syntax thoroughly.
In your addThisColumn function, your tabledata should be $scope.tabledata instead. This is the working function:
$scope.addThisColumn = function () {
$scope.tabledata.push({
Continent : $scope.continent,
ContinentId : $scope.continentid,
Country: $scope.country
})
};
Here is the working plunkr, I am sort of guessing this maybe what you want/need.
At the same time, you may want to read up on the official documentation of AngularJs.
you made some basic mistakes in your code. you didn't used your $scope variables correctly (e.g.: you tried to push into 'tabledata', not '$scope.tabledata').
in your last line tabledata.Countries.Country.push({ColumnIndex: $scope.columnindex}) (where you also should use $scope.tabledata) you are trying to push into Countries.Country, but there is no such field in Countries.
something like $scope.tabledata.Countries[$scope.country] would be possible i guess.
hope that helps, welcome on stackoverflow

MongoDB: Query and retrieve objects inside embedded array?

Let's say I have the following document schema in a collection called 'users':
{
name: 'John',
items: [ {}, {}, {}, ... ]
}
The 'items' array contains objects in the following format:
{
item_id: "1234",
name: "some item"
}
Each user can have multiple items embedded in the 'items' array.
Now, I want to be able to fetch an item by an item_id for a given user.
For example, I want to get the item with id "1234" that belong to the user with name "John".
Can I do this with mongoDB? I'd like to utilize its powerful array indexing, but I'm not sure if you can run queries on embedded arrays and return objects from the array instead of the document that contains it.
I know I can fetch users that have a certain item using {users.items.item_id: "1234"}. But I want to fetch the actual item from the array, not the user.
Alternatively, is there maybe a better way to organize this data so that I can easily get what I want? I'm still fairly new to mongodb.
Thanks for any help or advice you can provide.
The question is old, but the response has changed since the time. With MongoDB >= 2.2, you can do :
db.users.find( { name: "John"}, { items: { $elemMatch: { item_id: "1234" } } })
You will have :
{
name: "John",
items:
[
{
item_id: "1234",
name: "some item"
}
]
}
See Documentation of $elemMatch
There are a couple of things to note about this:
1) I find that the hardest thing for folks learning MongoDB is UN-learning the relational thinking that they're used to. Your data model looks to be the right one.
2) Normally, what you do with MongoDB is return the entire document into the client program, and then search for the portion of the document that you want on the client side using your client programming language.
In your example, you'd fetch the entire 'user' document and then iterate through the 'items[]' array on the client side.
3) If you want to return just the 'items[]' array, you can do so by using the 'Field Selection' syntax. See http://www.mongodb.org/display/DOCS/Querying#Querying-FieldSelection for details. Unfortunately, it will return the entire 'items[]' array, and not just one element of the array.
4) There is an existing Jira ticket to add this functionality: it is https://jira.mongodb.org/browse/SERVER-828 SERVER-828. It looks like it's been added to the latest 2.1 (development) branch: that means it will be available for production use when release 2.2 ships.
If this is an embedded array, then you can't retrieve its elements directly. The retrieved document will have form of a user (root document), although not all fields may be filled (depending on your query).
If you want to retrieve just that element, then you have to store it as a separate document in a separate collection. It will have one additional field, user_id (can be part of _id). Then it's trivial to do what you want.
A sample document might look like this:
{
_id: {user_id: ObjectId, item_id: "1234"},
name: "some item"
}
Note that this structure ensures uniqueness of item_id per user (I'm not sure you want this or not).

Resources