Let's say I have a service that provides a list of objects that I want to load as options in a <select> element.
The service method is myReferenceList.getCachedList().
It returns an array of objects of the following structure:
[
{
ReferenceId: "guid-1234",
ReferenceName: "some string",
SomeRandomRefField: 5
},
// etc...
]
In my controller I have a $scope.dataRow variable defined like so:
$scope.dataRow = {
ReferenceIdFk: "guid-2345",
// etc...
}
I want to load the select option list with data from myReferenceList.getCachedList(), with the displayed text coming from ReferenceName and the non-visible value coming from ReferenceId.
I want to hook this select item up to $scope.dataRow.ReferenceIdFk something like this:
ng-model="dataRow.ReferenceIdFk"
When all is said and done, and the data is loaded into $scope.dataRow.ReferenceIdFk, the select element should hold the selected object's ReferenceId value. When a user selects a different item in the select list, the value in $scope.dataRow.ReferenceIdFk should automagically get changed to the correct value.
How can I get this to work?
Loading the values into the select list is easy. Getting the automagic binding to the underlying data value in $scope.dataRow.ReferenceIdFk just doesn't seem to work.
Obviously, I can hand-jam in some procedural code to make this binding work, but I'm trying to understand how to declaratively make it work using angular features. Is it possible?
ng-options provides a micro-syntax to declare how to map objects in an array to display value and the selected result:
Angular's documentation provides the full syntax, but for your case the following should work:
<select ng-model="dataRow.ReferenceIdFk"
ng-options="i.ReferenceId as i.ReferenceName for i in myReferenceList.getCachedList()">
</select>
In a nutshell, the microsyntax is:
"<valueExp> as <displayExp> for <itemAlias> in <arrayExp>"
where:
arrayExp: is the expression that returns an array of values
itemAlias: is the alias for each item in an array; can be whatever you want
displayExp: a string expression that is used for each label; uses the itemAlias
valueEx: an expression whose value is assigned to ngModel-bound variable; uses itemAlias, and can return either a property of the item (itemAlias.prop as) or the item itself (itemAlias as)
Related
In my AngularJS project, I am having a dropdown field as a directive and the values are coming from the backend.The user can also leave the field without selecting the dropdown(optional field) but the problem is, there is no empty field from the backend. So I need to add an empty field into the dropdown as default.
Since there is no option in the directive got struck in this issue.Googled a lot but didnt get any solutions yet.Kindly provide some suggestion.
Note:Client machine,cant post the code.
If there is no value set for the ng-model that the dropdown is bound to, Angular will provide a blank option by default that can be left in place (ignored) by the user and will result in your final value being whatever you set that ng-model to in the first place. If you need an actual empty string for the value, initialize it to that.
If you need to enable the user to select an empty value once they have already selected a value, you will need to add an empty value to the object that the dropdown is bound to. Add the empty value like this:
myPromise.then(function(data){
$scope.ddInfo = data;
$scope.ddInfo.unshift({id:'0000',text:'Not Applicable'});
});
I am fetching some JSON frm a server and using it to populate a combobox.
A JSON entry looks like this
"campaign_id": "2",
"customer_id": "1",
"title": "Purple monkey dishwasher",
"description": "perfectly cromulent",
"start_time": "19/09/2015 09:42:06",
"end_time": "19/10/2015 09:42:06"
And I declare my drop down thus-wise
<select name="SelectCampaignForConnections"
ng-model="connectionsCampaignDropDown"
ng-options="campaign.title for campaign in campaigns"
ng-change="ShowConnectionsForCampaign(connectionsCampaignDropDown)">
I initialize the model of the select ...
$http.get(url)
.success(function(data, status, headers, config)
{
if ($scope.connections.length > 0)
$scope.connectionsCampaignDropDown = $scope.connections[0];
When the dropdown shows, it contains the title element of each JSON entry, BUT, it has an initial blank entry.
What am I doing wrongsomely?
[Update] #sheilak gave a good anser :
In order for the dropdown to defaulted to a non-blank value, the value
of the variable passed to ng-model must equal one of the options
passed to ng-options.
In your case where ng-options is populated by values of
campaign.title, it looks like the value passed to ng-model i.e.
connectionsCampaignDropDown should be populated with
$scope.connections[0].title rather than the whole object
$scope.connections[0].
$scope.connectionsCampaignDropDown = $scope.connections[0].title;
However, I would prefer to pass around an complete object, rather than just a field of it.
Can this be done?
(if not, then I will have to pass only the title to the ng-change function ShowConnectionsForCampaign() and it will then have to loop over the data to find a match, which seems inefficient)
<select name="SelectCampaignForConnections"
ng-init="justGiveItAName=getInitialSelection()"
ng-model="justGiveItAName"
ng-options="campaign.title for campaign in campaigns"
ng-change="ShowConnectionsForCampaign(justGiveItAName)">
where getInitialSelection() is a function on your scope that could take a param if you need it to, but I would probably go with something like this in the case you outline above:
function getInitialSelection() {return connections[0]};
or set it directly in the ng-init:
ng-init="$scope.connections[0]"
(you might have to fiddle with the above code - I haven't tested it).
btw - 'justGiveItAName' is then an object available elsewhere.
I have now tested it; see these Fiddles for working examples:
Setting directly in ng-init: http://jsfiddle.net/lukkea/nuo2c3Lk/
Using a function on the $scope: http://jsfiddle.net/lukkea/o6strxjf/
Passing the object instead of properties (as the OP requested): http://jsfiddle.net/lukkea/fsx8s67j/2/
Passing the objects in and object back: http://jsfiddle.net/lukkea/ww9yqsrm/3/
In order for the dropdown to defaulted to a non-blank value, the value of the variable passed to ng-model must equal one of the options passed to ng-options.
In your case where ng-options is populated by values of campaign.title, it looks like the value passed to ng-model i.e. connectionsCampaignDropDown should be populated with $scope.connections[0].title rather than the whole object $scope.connections[0].
$scope.connectionsCampaignDropDown = $scope.connections[0].title;
This should be possible, you just have to make sure that the initial value you set is the exact same object (not just another object with the same values)
You should be able to use campaign as campaign.title for campaign in campaigns in ng-options.
Then it stores the selected campaign object in the model (not just the value of campaign.title) and the label shown in the dropdown will still be campaign.title.
<select name="SelectCampaignForConnections"
ng-model="connectionsCampaignDropDown"
ng-options="campaign as campaign.title for campaign in campaigns"
ng-change="ShowConnectionsForCampaign(connectionsCampaignDropDown)">
The expression used here is: select as label for value in array.
select - the value stored in ng-model
label - the text displayed in the dropdown
The different expression options are listed in the official documentation.
Im working with a webservice and the returning JSON brings back some meta data that I use to define the layout of forms.
However, the JSON is continually evolving by the developers so currently where I target:
ng-repeat="cat in metaData[1].AcceptedValues"
To draw all the form structure...
Means that at some stage metaData Array element 1 may no longer hold the structure for this current form, it may be 2, 3 etc. JSON developer said he has now added additional data to identify each of the nodes under the value NAME
Under array element 1 I can now see Name : "ProductData" - and similarly under the other nodes different unique identifiers for Name
So basically I need to know how I can adjust my condition above to search for the metaData array element that contains the value Name = "ProductData" (or the value for the form I am rendering) and then any changes in array position is irrelevant.
Thanks
You can create a method to find the specified object:
$scope.getProductData = function() {
angular.forEach($scopem.metaData, function(item){
if(item.Name === "ProductData"){
return item.AcceptedValues;
}
});
return [];
};
Then use it in your markup:
ng-repeat="cat in getProductData()"
I think I have some sort of special code here as all I could google was "too simple" for my problem and it also didn't helped to come to a solution by myself, sadly.
I got a radio button group of 2 radios. I am iterating over "type" data from the backend to create the radio buttons.
My problem is the data binding: When I want to edit an object its "type" is set correctly, but not registered by the view so it doesn't select the desired option.
Follwing my situation:
Backend providing me this as "typeList":
[
{"text":"cool option","enumm":"COOL"},
{"text":"option maximus","enumm":"MAX"}
]
HTML Code:
<span ng-repeat="type in typeList track by type.enumm">
<input
type="radio"
name="type" required
ng-model="myCtrl.object.type"
ng-value="type">
{{type.text}}
</span>
Some Explanation
I don't want to use "naked" texts, I want to use some sort of identifier - in this case it is an enum. The chosen value shall be the entire "type", not only "type.text" as the backend expects type, and not a simple String.
So all I do with this is always a package thingy, the type.text is for like formatted/internationlized text etc.
A Pre-Selection works by setting this in the controller: this.object.type = typeList[0];
The first radio button is already selected, wonderful.
But why isn't it selected when editing the object. I made a "log" within the HTML with {{myCtrl.object.type}} and the result is {"text":"cool option","enumm":"COOL"}. The very same like when pre selecting. I already work with the same "technique" using select inputs, and it works fine. I also found some google results saying "use $parent because of parent/child scope". But 1) I didn't get that straight and 2) think it is not the problem here, as I use a controllers scope and not the $scope, or is this thinking wrong?
It might be explained badly, sorry if so, but I hope someone 1) get's what I want and 2) knows a solution for it.
Thank you!
If you're trying to bind to elements from an array, I believe you need to assign the actual elements from the array to your model property.
So this creates a new obj and sets it to $scope.selectedType (not what you want):
$scope.selectedType = {"text":"cool option","enumm":"COOL"};
whereas this assigns the first element of the array (which is what you want)
$scope.selectedType = $scope.typeList[0];
So to change the model, you can lookup the entry from the array and assign it to your model with something like this
$scope.selectedType = $scope.typeList.filter(...)
Here's a quick example of this approach http://plnkr.co/edit/wvq8yH7WIj7rH2SBI8qF
I am having a problem binding data retrieved from the server to a drop down list. The main issue I think is the fact that the comparison is done on differing object types.
For example:
1. The object returned from the server contains a currency code string. we want this to be bound to an item in the dropdown list
"baseCurrencyCode":"GBP"
The view model returns the list of currencies.. These are returned as a list of currency objects with different properties
{"currencies":[{"id":1,"rateId":0,"abbreviation":"AFN","description":"Afghani","rate":0.0,"rateDescription":null,"languageCode":"en-gb","isDefault":true,"fullDescription":"AFN - Afghani - ","shortDescription":"AFN - Afghani"}}
etc.
Currently, I have got this working by writing a function to go through every property for every item in the list, find the correct property we wish to compare to - do the comparison and then return the initial selection.
When calling my save method I then need to manually bind the currency abbreviation to the object I wish to return to the server.
Surely there must be a better way to do this?
Some of my code for reference..
<select ng-model="selectedCurrency" ng-options="currency.shortDescription for currency in viewModel.currencies"></select>
// Call to my custom method..List, PropertyName, value to compare
$scope.selectedCurrency = InitialiseDropdown($scope.viewModel.currencies, "abbreviation", $scope.updatedObject.baseCurrencyCode);
// Code executed when saving - to bind the currency to the updated object
$scope.updatedObject.baseCurrencyCode = $scope.selectedCurrency.abbreviation;
Any help is appreciated!
EDIT
Sorry if I wasn't clear enough.. To summarise..
The main problem here is binding to the drop down and initial selection.
The object we are updating contains a parameter (string) of the currency abbreviation.
The list we select from is a list of currency objects. As these are two differing object types I have been unable to plug in angulars 2 way binding and have written some code to do this on initial retrieval and when saving.
The cleanest way to fix this would be to return a currency object in our retrieval instead of a simple string of the abbreviation, but this is not an option.
Is there a better way of enabling 2 way binding on different object types ?
Thanks again
It is not exactly clear what the problem is, but you can save yourself some work by binding the <select> to the currently selected currency object (so you don't have to look it up later).
select + ngOptions allow you to bind to one value while displaying another, with the following syntax:
<select ng-model="selectedCurrency"
ng-options="currency as currency.shortDescription
for currency in viewModel.currencies">
</select>
In the above example, $scope.selectedCurrency will be bound to the whole currency object, but currency.shortDescription will be displayed in the dropdown.
See, also, this short demo.
UPDATE:
In case you don't need to bind to the whole currency object, but just bind updatedObject's baseCurrencyCode property to the abbreviation of the selected (in dropdown) currency, you can do it like this:
<!-- In the VIEW -->
<select ng-model="updatedObject.baseCurrencyCode"
ng-options="c.abbreviation as c.shortDescription
for c in currencies">
</select>
// In the CONTROLLER
$scope.currencies = [...];
$scope.updatedObject = {
...
baseCurrencyCode: <baseCurrencyCodeFromServer>
};
See, also, that short demo.
I have had the same problem, ng-model and ng-option being from 2 different sources. My ng-model is bound to a value in a json object representing a chosen filename and my ng-option is a list of possible values taken from a csv file.
In the controller I am reading a directory via a Nodejs route, and creating a json array of filenames like this
var allCsvFiles = [{"name":"file1.csv"},{"name","file2.csv},etc..]
The current csv file, i.e. the selected one is stored in another json array
[{"date":"01-06-2017","csvfile":"file1.csv","colour":"red"},{...}, etc].
I was using the following code for the dropdown:
<select type="text" ng-model="file.csvfile"
ng-options="opt.name for opt in allCsvFiles track by opt.name"></select>
Which caused the current selection to be blank and if I selected an item from the dropdown it put [object],[object] as the current selection. If I stepped through the code I found that it seemed to be selecting {"name","file1.csv"} as the option and couldn't display it, this seemed odd as my ng-options selection looks like it should just return the value of "name" not the array entry. I tried many different ways to make this work but eventually I found that if I made the list of possible selections a plain javascript array:
var allCsvFiles = ["file1.csv","file2.csv", "file3,csv]
and changed the select to:
<select type="text" ng-model="file.csvfile" ng-options="opt for opt in allCsvFiles"></select>
then the dropdown selection worked as expected.
I may have missed some other obvious solution here, but as the array of json objects is one dimensional anyway it doesn't seem to be an issue.
It looks like the OPs question has been answered, I just thought I'd add this as it solved it for me.