Im populating the values and display names for a select based on a JSON call. In the same call, I'm pulling from a nested array to get a default account value (if it exists).
so I have a scope that is holding that default account value, and the select is populating, but for the life of me, I can't figure out how to get the select attribute to apply to the object in the array that has a value that corresponds to the default value.
Essentially, I just want to apply "selected" to the option if the default account ID exists in the array.
Additionally, I cannot change the ng-model of the select because its tied into the form collection function.
Also, Im open to using ng-repeat vs ng-options, just couldn't figure it out with repeat so I moved to the options paradigm.
Any assistance would be grateful!
HTML:
<select class="form-control" id="authQAccount" name="authQAccount" ng-model="authFields.accountID" ng-init ng-options="item as item.name for item in accounts track by item.ID" ng-selected="$scope.defaultAcct" required>
</select>
In my controller:
$http.get('/api/assessment/authorize').success(function(data, status, headers, config) {
$scope.content = data.data;
//Pop the defaults and user options
$scope.languages = [];
angular.forEach(data.data.languages, function(value, key) {
$scope.languages.push(value);
});
$scope.accounts = [];
angular.forEach(data.data.accounts, function(value, key) {
$scope.accounts.push(value);
});
$scope.defaultAcct = data.data.defaultAccount;
The data Im getting:
"data": {
"defaultAccount": "6481004",
"defaultLanguage": "en_us",
"defaultAddonBody": "Test Email for Default",
"accounts": [{
"ID": "6481004",
"name": " ABC Company, Inc. "
}, {
"ID": "6481619",
"name": "EDF Company - Personal "
}
ng-selected only works on option elements and not on the select element itself. I don't think you can achieve what you want here with ng-options, if ng-model isn't set to a matching item then there's no way for the select to have that item selected.
Unless you only want it to appear selected, then you can add <option value="" ng-if="defaultAccount">{{defaultAccountName}}</option>. But then you'd have 2 items for the same value, you could either remove the default account from the list of options or keep the two items but with one of them prefixed as (Default). The second option lets users still select the default option without losing their choice later on, in case the default changes. This also means your form has the default selected without having to change the outer model.
Related
I am adding employee with designation field in dropdown (say 'Employee'). When I try to edit the profile of employee in another page the designation should display the pre-selected dropdown value with remaining values below.(the selected designation is not displaying first. it is shown as normal dropdown)
I have tried selected="selected"
<select class="form-control edited" id="designation_edit" name="designation_edit" ng-model="designation_edit">
<option value="HR" selected="selected">HR Executive</option>
<option value="Manager">Manager</option>
<option value="Employee">Employee</option>
<option value="Admin">Admin</option>
</select>
I have two modal boxes in my page. One for "add employee" and another for edit profile. When I add an employee with designation value from drop-down as employee, this selected value should be displayed first in edit page 'designation' drop-down with remaining values in the dropdown.
But currently, it is showing as normal dropdown in edit profile page. I need to fetch the selected value from add page and display here.
Help me to come out with this in angularjs.
Is it correct to add the below line in ajax call
$('#designation_edit').attr("selected":"selected");
I have tried:
$('#designation_edit').append('Designation Manager Employee Admin');
Simple way
If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:
$scope.Users = ["Suresh","Mahesh","Ramesh"];
$scope.selectedUser = $scope.Users[0];
Your HTML
<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>
complex example
Inside Controller:
$scope.JSON = {
"ResponseObject":
[{
"Name": "Suresh",
"userID": 1
},
{
"Name": "Mahesh",
"userID": 2
}]
};
$scope.selectedUser = $scope.JSON.ResponseObject[0];
Your HTML
<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>
To show selected value you can do as follows
Controller
assign a default value to the ng-model
$scope.empDesignationMapping = {
employee1 : "manager",
employee2 : "HR",
employee3: "Admin"
}
$scope.designation_edit = $scope.empDesignationMapping[employee1] // should be dynamic employee
HTML
<select ng-model="designation_edit" ng-selected="designation_edit" >
after that whenever you select something something it will show as selected.
I'm fairly new to Angular and was wondering how I can update a dropdown after doing an insert and have the new value selected?
I tried the following:
<select class="form-control" ng-model="selectedCompany" ng-change="GetCompany()"
ng-options="company.key as company.value for company in CompanyList">
<option value="">Select a Company</option>
</select>
This populates a list of companies when the page 1st loads and the inserted data is returned to scope + it's id.
To add the new value without refreshing the page, I'm trying the following non-working (almost) code:
var key = $scope.company.id;
var value = $scope.company.name;
$scope.CompanyList.push({ key: value });
$scope.selectedCompany = $scope.company.id;
This seems to add a value to the dropdown, but it's showing up blank. It's also not selecting the blank value (which should be the new company name), any help would be appreciated.
It seems that when you create the new company object, you need to assign the value property which is the display name.
Here's a code snippet:
angular.module("myApp", [])
.controller("testCtrl", function() {
this.companyList = [{
key: 1,
value: "Company A"
}];
var ctrl = this;
this.addCompany = function() {
ctrl.companyList.push({key:2, value:"Company B"});
ctrl.selectedCompany = 2;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="testCtrl as ctrl">
<select class="form-control"
ng-model="ctrl.selectedCompany"
ng-options="company.key as company.value for company in ctrl.companyList">
<option value="" disabled>Select a Company</option>
</select>
<button ng-click="ctrl.addCompany()">
Add company B and select it
</button>
</div>
Ok, so what do we have here?
You're creating your options with the ngOptions directive like this: ng-options="company.key as company.value for company in CompanyList"
That mean that the array $scope.CompanyList must have objects with a key property that will be set to the option value attribute, and a value that will be the option display value (Or label, if you prefer to call it that way).
What you were doing wrong: You added an object with only one property named key and set its value with the value variable: $scope.CompanyList.push({ key: value });
How should you fix it: You need to append object(s) with a key and a value like so: $scope.CompanyList.push({ key: key, value: value });
The following line push an object, which has a property name "key" set to value:
$scope.CompanyList.push({ key: value });
The result will be:
{'key': $scope.company.name}
You may change it to:
$scope.CompanyList.push({key: key, value: value});
Which will result in:
{ 'key': $scope.company.id, 'value': $scope.company.name }
I'm new to angular, and struggling with updating bound values from a select box that is inside a modal which is populated based on a particular row of data that is "edited" in a table. Currently, I can click edit, the select box populates with the correct values and selected option based on the user row I "edited". My problem is I can update either the ID or the Title of my model but not both. Here is my html select:
<select ng-model="user.team">
<option ng-selected="{{x.id}} === user.team.id" ng-repeat="x in teams" ng-selected="{{x.id}} == {{user.team.id}}" value="{{x.id}}">{{x.title}}</option>
</select>
Note that if I make ng-model="user.team.id" it updates the id correctly in my list, and "user.team.title" updates the title correctly. My scope/model is defined as such and I would like to update both id and title when the option is changed:
$scope.user = {
team :{
id: '',
title: ''
}
};
Can't you just do:
<select ng-model="user.team" ng-options="x.title for x in teams track by x.id"></select>
ng-model will set the initial selection to the option that matches user.team
Please look at the following jsbin. I have a select input that has two options (Ohio, NewYork). Within the ng-options for the Select, I am selecting the entire object and NOT just the name or key value. I need both.
When I select Ohio (for example), the model correctly updates showing the selected object:
"birthState": {
"Key": "1",
"Value": "Ohio"
}
If I add this code to the model within my controller (setting the field to 'Ohio' by default), the select does not reflect this default setting.
What am I doing wrong that is preventing me from giving this dropdown a default value?
You are not able to select because, all objects will have unique id. objects in options array and object assigned in model (in controller) will be different in this way.
To achieve what you wanted, try adding track by option.Key in ng-options, and assign Key for 'birthState' field of model inside controller.
<script type="text/ng-template" id="select.html">
<select required type="number" ng-model="model[options.key]" ng-options="option.Value for option in to.options track by option.Key">
<option value="">Select One</option>
</select>
</script>
inside controller
vm.model = {
"birthState": {Key: '3'}
};
I'm trying to render select box and it does not work as expected - options values are incorrect. I checked manual, according to it the syntax for array (in my case array of objects) is
select as label for value in array
So here is what i'm doing:
data:
[{"id":"3","name":"asdasd","code":"asdads","group":"2","cost":"0"},{"id":"4","name":"adrf fg df ","code":"dasfasd","group":"2","cost":"0"}]
template:
<select ng-model="productToBuy" ng-options="item.id as item.id for item in products"></select>
rendered result:
<select ng-model="productToBuy" ng-options="item.id as item.id for item in products" class="ng-pristine ng-valid">
<option value="0" selected="selected">3</option>
<option value="1">4</option>
</select>
as we can see, options values does not set to items's id.
Also this may be not proper syntax when source is array but i having same results when trying like this:
<select ng-model="productToBuy" ng-options="item.id as item.id for (key, item) in products"></select>
I put this code on jsfiddle. Any help appreciated.
This is the behavior of the ngOptions directive (the output you are seeing, where the value is the index of the item and not the id property that you are trying to pass in from your code sample). ngOptions will data-bind the selected option to the variable that you specified in ngModel. You would then work with your data bound variable instead of the "value" of the option element itself.
Html:
<select ng-model="selected" ng-options="item.name for item in items"></select> {{ selected }}
JS:
$scope.items = [
{"id": "3","name":"asdasd","code":"asdads","group":"2","cost":"0"},
{"id": "4","name":"adrf fg df ","code":"dasfasd","group":"2","cost":"0"}
];
In the above example, $scope.selected would represent the actual selected item. You can then access any of the selected item's properties: $scope.selected.name, $scope.selected.code... etc.
If you needed to preselect an item with the above example, you could do the following:
$scope.items = [
{"id": "3","name":"asdasd","code":"asdads","group":"2","cost":"0"},
{"id": "4","name":"adrf fg df ","code":"dasfasd","group":"2","cost":"0"}
];
$scope.selected = $scope.items[1]; // Pre-selected the 2nd item in your array
If you still need to have full control over your value attributes, you're better off using the ng-repeat directive, but remember if you do this, your selected items won't be data bound to your model.
EDIT: Note on 'select as label for value in array' syntax:
In case its helpful, what your "item.id as item.name for item in products" was doing was actually setting your variable in the ngModel directive to the value you specify in the select portion of the syntax. So what that expression is doing is setting the label as item.name, but binding $scope.selected to the value of item.id, rather than to the entire instance of item itself. So if your first item in the examples above was selected, $scope.selected would be equal to "3". It doesn't actually change the value attribute of the option element itself.
Your datatype in the JSON object for the id is a string and the value of $scope.selected is integer. If you switch one of them to the other it would work fine!
The value of the options will still be 0 and 1, but the databinding of Angular does the trick for you and binds the value you have specified in your expression (item.id as item.name) to the ng-model of your parent element (the select element).
If you don't need ng-model of select element and you want to use selected value of select element, then implement it in this way:
<select>
<option ng-repeat="item in items" value="{{item.value}}">
{{item.text}}
</option>
</select>