Angularjs default value for bound select [duplicate] - combobox

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to make a preselection for a select list generated by AngularJS?
In the angular tutorial they set a sortOrder scope variable that defaults the sort by select to 'Newest'.
In my fiddle I am doing similar but my select value is not selected. Instead i get the blank entry as if i did not set any value in the scope. Yet I can see my sort order and i am emitting the value of the select and it is preset.
//set a default this way also, but not updating the dropdown
$scope.ddlFilter = {
name: "All Open Events",//doesn't matter what this is, only cares about value
value: "ALL"//"OPEN"
};
I know i can use ng-init to set defaults but i want to be able to do it this way as well.
Any suggestions?

Try using an object instead of an array of objects. It will allow you to reference what you want by a string vs. an array position such as scope.eventFilters[0].
$scope.eventFilters = {
"OPEN": "All Open Events",
"UNMAPPED": "All Un-Mapped Events",
"MAPPED": "All Mapped Events",
"CLOSED": "All Closed Events (past 8 hours)",
"ALL": "All Events",
"OTHER": "Other OpCenter Open Events"
};
And then define the default value as a string (key for the object above):
$scope.ddlFilter = "MAPPED";
And then on the page change your select to
<select ng-model="ddlFilter" ng-options="k as v for (k, v) in eventFilters"></select>
and your filter no longer needs a .value, so it will become:
<tr ng:repeat="event in events | myEventFilter:ddlFilter | orderBy:sort.column:sort.descending">
See your modified code working here: http://jsfiddle.net/WXLte/2/

Related

how to update or insert many objects in an array subdocument in mongodb? [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
the document model I'm using is as follows.
{
"_id" : "a301c595-f6f3-4ede-91c5-f1cabd548338",
"UserName" : "3#3.com",
"Revision" : 6,
"UserVocabs" : [
{
"Vocab" : "apple",
"LearnStatus" : 0,
"lastChanged" : 213232
},
{
"Vocab" : "book",
"LearnStatus" : 0,
"lastChanged" : 213132
},
]
}
I'm trying to add or replace objects in the UserVocabs array by their Vocab field so I don't know their indexes. till now the only solution I used is to first pull the object and then trying to push its updated version back in the array. but it needs 2 query for each object updates. is there any better solution out there?
You could update one of the elements of array by its index like
db.test.update({"_id": "a301c595-f6f3-4ede-91c5-f1cabd548338"},{$set:{"UserVocabs.1.Vocab":"orange"}})
Or if you want to modify all the elements you could replace the 1 with $ which is a wildcard of an arbitrary index. (you may have to set the last two parameters tags to make this work though)
and could extends the array with
db.test.update({"_id": "a301c595-f6f3-4ede-91c5-f1cabd548338"},{$addToSet:{"UserVocabs":{"key1":"value1","key2":"value2"}}})
Removable of elements could ref to this answer
If you want to use the value of array to find the elem to replace you could:
db.test.update({"UserVocabs.Vocab": "apple"},{$set:{"UserVocabs.$.Vocab":"orange"}})

Replace , with . in input field bound to property using Angular 1

I have an input field that is supposed to contain numbers.
It is bound to an object property.
I want input entered as 4,5 to automatically get converted to 4.5 in both model and view.
HTML:
<input data-ng-model="productContent(product.Id).Org" value="{{productContent(product.Id).Org | replaceComma}}" />
Control:
$scope.productContent = function (prodId) {
var content = $.grep($scope.productsContent, function (el) { return el.ProdId === prodId });
return content[0];}
Filter:
app.filter('replaceComma', function () {
return function (val) {
return (typeof val) == "string" ? val.toString().trim().replace(",", ".") : val
};
});
Result:
When I enter a number, at first the model (productContent) retrieves the correct object. Then the filter code is called and returns a correctly converted string. I would expect both the model and view to be updated to the filtered value, but both are updated with the unfiltered value. What am I doing wrong?
I have faced the same problem in the past but instead of creating my own filter, I took a different path and found something ready to use instead.
angular-input-masks by assisrafael one of my favourite angular extensions for this purpose:
https://github.com/assisrafael/angular-input-masks
Examples:
http://assisrafael.github.io/angular-input-masks/
Since the author has written the documentation, I don't want to get extensive on it and be outdated in the future. As a quick reference, look for ui-number-mask.
Maybe this is not a direct answer to your question, since it's not replacing commas with periods, but making you type the decimals instead.
On a side note, you can suppress the thousands separators with ui-hide-group-sep
I hope that's helpful, otherwise leave a comment and I'll be happy to continue to assist you!
-Helvio

Angular 2: Create drop-down list with array of dictionaries [duplicate]

This question already has an answer here:
Error if don't check if {{object.field}} exists
(1 answer)
Closed 6 years ago.
I'm using options tag in Angular 2 to populate my dropdown list. The dropdown list is populating correctly with dateTest1.json, however, when iterating thru the values of a given key in a .json file, then it's having trouble populating the drop down list. What's the correct way in Angular 2 for populating dropdown list with dateTest.json example below?
*.component.html when retrieving from dateTest.json: EXCEPTION: TypeError: Cannot read property 'month' of undefined in [dateAttributesList.month in *Component#63:22]
<option *ngFor="#m of dateAttributesList.month" [value]="m">{{m}}</option>
dateTest.json:
[
{"month": ["Dec", "Jan", ...]},
{"day" : ["1","2"...]}
]
*.component.html when retrieving from dateTest1.json: correctly populating
<option *ngFor="#m of dateAttributesList" [value]="m">{{m}}</option>
dateTest1.json:
[
{"month": "Dec"},
{"month": "Jan"},
{"month": "Feb"},
...
]
Use the safe navigation operator if the value you bind to is passed by an input or fetched by an async call:
<option *ngFor="#m of dateAttributesList?.month" [value]="m.month">{{m}}</option>
[value] only supports string values. If you have object values use [ngValue]
<option *ngFor="#m of dateAttributesList" [ngValue]="m.month">{{m}}</option>
[ngValue] only works with [ngModel]

Angular select adding empty element despite carefulness

I have this html:
<select ng-model="group.newCriterionType">
<option ng-repeat="type in group.availableTypes" value="{{type}}" ng-selected="$first">{{type}}</option>
</select>
And this model code (using jresig's Class mini-library)
var FilterGroup = Class.extend({
className: 'FilterGroup',
widgetType: 'group',
init: function(name) {
this.name = name;
this.availableTypes = FilterTypes;
this.newCriterionType = this.availableTypes[0];
this.updateAvailableTypes();
},
});
However, I still get an empty element in my select. According to all the answers I've seen on SO so far, this is apparently the behaviour of when your model value contains an incorrect value. However:
I added in some console.log statements to check the value
This code is definitely being called because availableTypes is being set
It's pulling it from the array it's looping from. How can this be an incorrect value?
It persists even if i pull the ng-selected out
It persists if I use ng-options instead of looping through them (though that then means i can't set the value to the be the same as the text without turning it into an object)
Any clues much appreciated.
James

Angularjs autoselect dropdowns from model

I'm trying display some data loaded from a datastore and it's not reflecting changes on the UI. I created an example to show a general idea of what I'm trying to achieve.
http://plnkr.co/edit/MBHo88
Here is the link to angularjs example where they show when on click then dropdowns are clear out. If you replace the expression with one of the colors of the list dropdowns are well selected. Does this type of selection only work on user events?
http://docs.angularjs.org/api/ng.directive:select
Help is appreciated!!!
Actually the problem is that ngSelect compares objects using simple comparition operator ('=='), so two objects with same fields and values are considered as different objects.
So you better use strings and numbers as values ('select' parameter in expression of ngSelect directive).
Here is kind of solution for your plunker.
Aslo there are some discussion about this topic on GitHub:
https://github.com/angular/angular.js/issues/1302
https://github.com/angular/angular.js/issues/1032
Also as I headred there is some work in progress about adding custom comparor/hashing for ngSelect to be able to use ngSelect more easier on objects.
One mistake in the initialization of your controller. You have to refer to the objects in your palette, since these are watched on the view:
$scope.selectedColors.push({col: $scope.palette[2]});
$scope.selectedColors.push({col: $scope.palette[1]});
Same with your result:
$scope.result = { color: $scope.obj.codes[2] };
Then you need to watch the result. In the below example, select 1 receives the value from the initiating select, the second receives the value below in the palette. I don't know if that's what you wanted, but you can easily change it:
$scope.$watch('result', function(value) {
if(value) {
var index = value.color.code -1;
$scope.selectedColors[0] = {col: $scope.palette[index] };
$scope.selectedColors[1] = {col: $scope.palette[Math.max(index-1, 0)] };
}
}, true);
See plunkr.
Ok, I think I figured this out but thanks to #ValentynShybanov and #asgoth.
According to angularjs example ngModel is initialized with one of the objects from the array utilized in the dropdown population. So having an array as:
$scope.locations = [{ state: 'FL', city: 'Tampa'}, {state: 'FL', city: 'Sarasota'} ....];
And the dropdown is defined as:
<select ng-options="l.state group by l.city for l in locations" ng-model="city" required></select>
Then $scope.city is initialized as:
$scope.city = $scope.locations[0];
So far so good, right?!!!.. But I have multiple locations therefore multiple dropdowns. Also users can add/remove more. Like creating a table dynamically. And also, I needed to load data from the datastore.
Although I was building and assigning a similar value (e.g: Values from data store --> State = FL, City = Tampa; Therefore --> { state : 'FL', city : 'Tampa' }), angularjs wasn't able to match the value. I tried diff ways, like just assigning { city : 'Tampa' } or 'Tampa' or and or and or...
So what I did.. and I know is sort of nasty but works so far.. is to write a lookup function to return the value from $scope.locations. Thus I have:
$scope.lookupLocation = function(state, city){
for(var k = 0; k < $scope.locations.length; k++){
if($scope.locations[k].state == state && $scope.locations[k].city == city)
return $scope.locations[k];
}
return $scope.locations[0]; //-- default value if none matched
}
so, when I load the data from the datastore (data in json format) I call the lookupLocation function like:
$scope.city = $scope.lookupLocation(results[indexFromSomeLoop].location.state, results[indexFromSomeLoop].location.city);
And that preselects my values when loading data. This is what worked for me.
Thanks

Resources