From this example
I'm trying to set the select value from my controller and this doesn't work for me even when I set the id as explained in many questions here. The only difference is that I have a default value set with ng-init. How do I set the value from the controller?
DOM:
<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)">
<option value="0">-- All orders --</option>
<option ng-repeat="obj in orders" value="{{ obj.id }}">{{ obj.name }}</option>
</select>
JS inside a function:
$scope.orders = data;
$scope.storeorder = parseInt($scope.order); // Tried without parseInt also
console.log($scope.storeorder) returns the right value, but it doesn't set the right value in the browser DOM.
If you don't want to use ng-options(which is the right way) , you can try with
ng-selected : Working Demo : http://jsfiddle.net/nf2m0rr1/
Example :
<body ng-app ng-controller="OrderCtrl">
<div>Order is: {{storeorder}}</div>
<select ng-model="storeorder">
<option ng-selected="{{order.value == storeorder}}" ng-repeat="order in orders" value="{{order.value}}">{{order.displayName}}</option>
</select>
</body>
function OrderCtrl($scope) {
$scope.storeorder = 2;
$scope.orders = [{
value: '1',
displayName: 'Order One'
}, {
value: '2',
displayName: 'Order Two'
}]
}
Use ng-options:
<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)" ng-options="obj.id as obj.name for obj in orders">
ng-options solved 50% of the problem but I still needed to handle the default value in the DOM and change the ng-init option. This was really bugging me. Here's the complete solution which enabled me to not set anything from the controller:
<select ng-model="storeorder" ng-options="orderdata.id as orderdata.name for orderdata in orders" ng-init="storeorder = order == 0 ? 0 : order" ng-if="orders.length > 0" ng-change="storeOrderChange(storeorder)">
<option value="">-- All orders --</option>
</select>
Related
I'm working on a project, and I need to bind the options value to object key's in such a manner that, on selecting an option, it gives 1, else other variables remain 0.
My HTML Code:-
<select required class="custom-select">
<option disabled>Select an option</option>
<option ng-model="PredictCtrl.detail.building_type_AP">Apartment</option>
<option ng-model="PredictCtrl.detail.building_type_GC">Independent House / Villa</option>
<option ng-model="PredictCtrl.detail.building_type_IF">Independent Floor / Builder's Floor</option>
<option ng-model="PredictCtrl.detail.building_type_IH">Gated Community Villa</option>
</select>
Variable to bind -
PredictCtrl.detail = {
building_type_AP: 0,
building_type_GC: 0,
building_type_IF: 0,
building_type_IH: 0
}
Generally, binding is done with select tag, which gives the value of the selected option, but I want in such a way that, when I click on Apartment option, it's bind variable PredictCtrl.detail.building_type_AP becomes 1, rest remains 0. Similarly, it does with other options.
I want to send the data as the same format through API.
So, please Help me out.
Sorry If I was not very clear with explaining or for any typo.
Thank you in advance.
You should take a look at the NgOptions directive which is the "angularjs" way of working with the select-tag.
It sould be able to fulfill your requirement as you will get the selected option in the SelectedOption object.
Here's an example
angular.module("app",[]).controller("myCtrl",function($scope){
$scope.details =
[
{name:"Apartment", value:1},
{name:"Independent House / Villa", value:2},
{name:"Independent Floor / Builder's Floor", value:3},
{name:"Gated Community Villa", value:4}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select required class="custom-select" ng-options="item as item.name for item in details" ng-model="selectedOption">
</select>
<p>SelectedOption: {{selectedOption}}</p>
</div>
None of the answers at my time of writing actually present a functioning solution, so here's one.
Don't scatter ng-model directives across different option elements, it's unnecessary.
You can achieve what you want by using ng-options to enumerate all your choices, a single ng-model to keep track of the selected option, and ng-change to apply the values as you described (i.e. 1 on the selected key, 0 for everything else).
I've assumed you've got a requirement to keep the structure of detail as is. If it can be changed, then I'd recommend associating each labels with each it's respective building_type_ to keep things together.
See below.
angular
.module('app', [])
.controller('PredictCtrl', function () {
this.selectedDetail = null;
this.detail = {
building_type_AP: 0,
building_type_GC: 0,
building_type_IF: 0,
building_type_IH: 0,
};
this.labels = {
building_type_AP: 'Apartment',
building_type_GC: 'Independent House / Villa',
building_type_IF: 'Independent Floor / Builder\'s Floor',
building_type_IH: 'Gated Community Villa',
};
this.changeDetail = function () {
for (var key in this.detail) {
this.detail[key] = +(this.selectedDetail === key);
}
};
});
<script src="https://unpkg.com/angular#1.7.4/angular.min.js"></script>
<div ng-app="app" ng-controller="PredictCtrl as PredictCtrl">
<select
ng-model="PredictCtrl.selectedDetail"
ng-options="key as PredictCtrl.labels[key] for (key, value) in PredictCtrl.detail"
ng-change="PredictCtrl.changeDetail()"></select>
<pre>{{ PredictCtrl.detail | json }}</pre>
</div>
try like this:
in your controller:
$scope.details = [
{
name: "building_type_AP",
value: "Apartment",
state: false
},{
name: "building_type_GC",
value: "Independent House / Villa",
state: false
}/*add more here*/
];
$scope.setActive = function(detail){
detail.state = !detail.state;
}
in html template:
<select required class="custom-select">
<option disabled>Select an option</option>
<option ng-repeat="detail in details" ng-click="setActive(detail)">{{detail.value}}</option>
</select>
in the end just go through $scope.details and parse false to 0 and true to 1 OR just do this inside setActive function
I have an html list with a form for defining filter values. In this form there is a select box:
<div style="...">
<label for="lstCategory">Category:</label><br/>
<select name="category" id="lstCategory" ng-model="category" ng-change="loadActivities()">
<option value="0">default1</option>
<option value="1">default2</option>
<option ng-repeat="category in categories" value="{{ category.id }}">{{ category.id }}</option>
</select>
</div>
In my controller I bind the "categories" model to a REST resource:
.controller('AppointmentsHomeCtrl', [
...
function(
...
) {
$scope.location = typeof $location.search().location != 'undefined' ?
$location.search().location :
'0';
$scope.category = typeof $location.search().category != 'undefined' ?
$location.search().category :
'0';
$scope.categories = CategoriesResource.query();
Now I want to preselect a value in this select box, depending on the dearch parameter "location" in my url, which is done by the $scope.category = typeof $locati....... part of the code.
My problem is, that this preselection isn't reflected to my HTML while the mnodel itself has the correct value.
I already tryed to set the value after the query to the resource is done by watching the resource or giving a callback function to the "query" method but this also isn't working.
Did I missed something here? What is the correct way to solve this problem?
Edit:
It seems to recognise the options since:
$scope.category = "foo"; adds a pseudo option which gets selected.
But when I choose an existiong id, nothing happens at all:
$scope.category = "3";
at controller you can try this method for preselect value
$scope.precategory = '0'; //just for example value
then on your html code make sure ng-model having different variable with ng-repeat like this one
<select name="category" id="lstCategory" ng-model="precategory " ng-change="loadActivities()">
<option value="0">default1</option>
<option value="1">default2</option>
<option ng-repeat="category in categories" value="{{ category.id }}">{{ category.id }}</option>
that method will help solve your problem, because i was getting same problem before :)
Instead of $scope.categories = CategoriesResource.query(); try:
CategoriesResource.query().then(function(result) {
$scope.categories = result;
});
You may have to tweak it a bit if the result is not an array...
My problem is that ng-selected is set as true but the option is not getting selected
This is my controller code
.controller("PendingInvoiceCtrl", function($scope, $location, safeApply, dataService) {
var userData = dataService.data();
var mauth_token = userData.mauthToken;
var mauth_acntId = userData.thisApartment.account;
var apt_id = userData.thisApartment.id;
$scope.house_list = userData.thisApartment.house;
$scope.selectedHouseId = $location.search().houseId;
console.log($scope.selectedHouseId);
});
This is my HTML code
<select ng-model="selectedHouseId">
<option ng-repeat="house in house_list" ng-selected="{{ house.house_id == selectedHouseId }}" value="{{ house.house_id }}">
{{ house.house_display_name }}
</option>
</select>
And below is my data format
{
house:[0]:{
house_display_name: "paras, 101",
house_id: "520755"
}
}
The ng- attributes don't need the extra curly braces. Try:
<option ng-repeat="house in house_list" ng-selected="house.house_id == selectedHouseId" ng-value="house.house_id">
{{house.house_display_name}}
</option>
A better approach would be to use the ng-options possibility of the select tag. This would result in:
<select
ng-model="selectedHouseId"
ng-options="house.house_id as house.house_display_name for house in house_list">
</select>
And then you don't need to manually worry about the selected attribute for the options, as it will select the one depending on the value of the model.
Your option tag should be:
<option ng-repeat="house in house_list" ng-selected="house.house_id == selectedHouseId" ng-value="house.house_id">
if you use ng-Selected and ng-Model together was never really specified. It looks like at some point ng-Model took priority over ng-Selected.
I recommend you to use the Angular Directive ng-options.
<select ng-options="house.house_id as house.house_display_name for house in house_list" ng-model="selectedHouseId"></select>
Associated plunker: http://plnkr.co/8LGz5o0d2gDRoRHYr4pQ
I'm pretty new to Angular and trying the ng-options. In my controller, I have:
$scope.permissionLevels = [
{ value: "ROLE_READ", text: "Read Only" },
{ value: "ROLE_WRITE", text: "Write" }
];
In my template, I have:
<select ng-options="permissionLevel.text for permissionLevel in permissionLevels"
ng-model="selectedValue"></select>
Depending on the view, I want to hide either Read or Write. So in my controller, I have another flag that indicates what view it is. Before I used ng-options, I had a normal select drop down and did something like this:
<select>
<option>Read Only </option>
<option ng-show="shouldShowWrite">Write </option>
</select>
Is there a way to do this with ng-options? Thanks.
You could use a filter in the ngOptions expression:
<select ng-model="selectedValue"
ng-options="permissionLevel.text for permissionLevel in
permissionLevels | filter:shouldShow">
</select>
and define the shouldShow() function to $scope in the controller:
$scope.shouldShow = function (permissionLevel) {
// put your authorization logic here
return $scope.permission.canWrite || permissionLevel.value !== 'ROLE_WRITE';
}
For the full example see: http://plnkr.co/edit/8FkVktDXKGg3MQQawZCH
Consider ngRepeat for that level of control. I don't think it's possible with ngOptions.
<select ng-model="selectedValue">
<option ng-repeat="permissionLevel in permissionLevels" value="{{permissionLevel.text}}" ng-show="shouldShowWrite(permissionLevel)">
{{permissionLevel.text}}
</option>
</select>
Plaese check below code, it may help you to solve the problem!!
<select>
<option>Read Only </option>
<option ng-show="selectedValue.value=='ROLE_WRITE'">Write </option>
</select>
Let my HTML is as follows:
<div ng-repeat="option in options">
<select ng-model="myselect">
<option value="">{{option.attribute_text}}:</option>
<option value="">{{option.attr_value}}-${{option.cost}}</option>
</select>
</div>
I want to get the values of the option selected in the ng-model. Is there any methods to get the values in the ng-model under a ng-repeat?
You have multiple selects and you are giving same model to all of them.
you can't give them same myselect to all of them.
give each option(the ones you are repeating) a name, and use an object's keys for their model.
<div ng-repeat="option in options">
<select ng-model="selections[option.name]">
<option value="">{{option.attribute_text}}:</option>
<option value="">{{option.attr_value}}-${{option.cost}}</option>
</select>
</div>
then you can access them like $scope.selections["some option name you gave earlier"]
if you want to use select you can use ng-select
if you specify ng-model for ng-select it bind the select option to ng-model
you can see it in this jsbin
Have a look at: https://docs.angularjs.org/api/ng/directive/select
Here's an example that should be about right:
Options stored as list of hashes in your controller:
$scope.options = [ { "attribute_text" : "whatever", "data" : { "value" : 9, "cost" : 8 }, { ... } ]
// Selected value
$scope.optionSelected = {};
HTML:
<div>
<select ng-select="option.attribute_text for option in options" ng-model="optionSelected">
</div>