I have dropdown selection menu & want to send the dropdown selected value in request params of api. My code is...
<select class="form-control" id = "SelectionInput_reason">
<option name="careerType" value="type_1">Career</option>
<option name="examType" value="type_2">Exams</option>
</select>
getValue = function() {
var selectedValue = this.value;
var selectedText = this.options[this.selectedIndex].getAttribute('name');
alert(selectedValue);
alert(selectedText);
}
document.getElementById('SelectionInput_reason').addEventListener('change', getValue );
Please give answer in angularJS if possible...
also how can I get the text input of tinymceeditor in a variable ?
$scope.tinymceModel = 'Initial content';
$scope.getContent = function() {
console.log('Editor content:', $scope.tinymceModel);
};
$scope.setContent = function() {
$scope.tinymceModel = 'Time: ' + (new Date());
};
$scope.tinymceOptions = {
selector: 'textarea',
//plugins: 'link image code',
toolbar: ' bold italic | undo redo | alignleft aligncenter alignright | code'
};
HTML is..
<div class="form-group">
<textarea ui-tinymce="tinymceOptions" id="jander" ng-model="tinymceModel" placeholder="Ask your question" class="form-control"></textarea>
</div>
Bind a model in your select dropdown. Like below
<select class="form-control" id = "SelectionInput_reason" data-ng-model="inputReason">
In your controller you will get selected option
console.log($scope.inputReason)
Here is a sample code with a fiddle attached
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.shelf = [{
'name': 'Banana',
'value': '$2'
}, {
'name': 'Apple',
'value': '$8'
}, {
'name': 'Pineapple',
'value': '$5'
}, {
'name': 'Blueberry',
'value': '$3'
}];
$scope.cart = {
'fruit': $scope.shelf[0]
};
});
<div ng-controller="MyCtrl">
<div>
Fruit List:
<select ng-model="cart.fruit" ng-options="state as state.name for state in shelf"></select>
<br/>
<tt>Cost & Fruit selected: {{cart.fruit}}</tt>
</div>
</div>
Fiddle link : http://jsfiddle.net/Td2NZ/1867/
My advise in this scenario is try to keep all input choices as a Js Object (Like $scope.shelf in this code) cause thats what Angular is built for rigid and robust handling of the data, eventually you could just load those options from a server or json file and not having to touch your HTML at all!
Hope this helps!
Related
I currently have a select in an angular app :
http://jsfiddle.net/4qKyx/251/
And I'm trying to manage my select depending on the number of result.
HTML
<div ng-controller="MyCtrl">
<select ng-model="form.type" required="required" ng-options="option.value as option.name for option in typeOptions" >
</select>
</div>
JS
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.typeOptions = [
{ name: 'Feature', value: 'feature' },
{ name: 'Bug', value: 'bug' },
{ name: 'Enhancement', value: 'enhancement' }
];
if($scope.typeOptions.length == 1){
$scope.form = {type : $scope.typeOptions[0].value};
}else{
// first option set to "select an option" and null -> won't work with required
}
}
If I have only one element in my typeOptions, i want the only option to be pre-selected. Now if I have more than one element, I want an option saying "Select an option" but which can't be let selected in a required select. Thank you in advance for any help !
Can you try you controller code as like below,
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.form = {};
$scope.typeOptions = [
{ name: 'Feature', value: 'feature' },
{ name: 'Bug', value: 'bug' },
{ name: 'Enhancement', value: 'enhancement' }
];
$scope.form.type=($scope.typeOptions.length===1) ? $scope.typeOptions[0].value : '';
}
also updated your jsfiddler
The code you've provided on SO works.
Your issue is only on the fiddler with the line
<option style="display:none" value="">select a type</option>
if you want your "placeholder" inside the select, you can do it like that :
if($scope.typeOptions.length == 1){
$scope.form = {type : $scope.typeOptions[0].value};
}else{
$scope.typeOptions.unshift( { name: 'Select a value', value: '' });
}
you can add option element to your select to be like
<select ng-model="" required
ng-options="option.value for option in typeOptions">
<option value=''>- Please Choose -</option>
</select>
and just do the check in you controller if the options.length equals 1 then set the ng-model the good thing is the required validation still works.
here is jsfiddle
if you removed the comment it show select option
I have a dropdown with some values :
Apple
Mango
Orange
Grapes
HTML :
<div class="form-group">
<label class="control-label col-sm-20" for="groupz">Role*</label>
<select class="form-control" ng-model="model.selectedRole" name="role" ng-change="GetRole(model.selectedRole)" >
<option value class selected>Select Roles</option>
<option ng-repeat="item in model.roles track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
I want my $scope.selectedRole to be by default as Apple. But later when the user needs to change the value, they can change it from apple to orange or any other fruit name. I have separate service request to fetch the fruits from backend and I write my code in controller as follows.
$scope.GetRole = function() {
$scope.selectedrole = [];
if ($scope.model.selectedRole != null) {
for (var i = 0; i < 1; i++) {
$scope.selectedrole.push($scope.model.selectedRole);
}
}
}
I hope this helps you
JsFiddle
In js
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.selectedrole = ['Apple', 'Mango', 'Orange', 'Grapes'];
$scope.selectRole= $scope.selectedrole[0];
});
In HTML
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<select ng-model="selectRole" ng-options="role for role in selectedrole">
</select>
</div>
just try : HTML
<select class="form-control select" name="role" id="role" data-ng-model="ctrl.model.selectedRole" data-ng-options="option.name for option in ctrl.model.roles track by option.id"></select>
in your contoller
$scope.model = {
roles: [{
id: '1',
name: 'Apple'
}, {
id: '2',
name: 'Orange'
}, {
id: '3',
name: 'Mango'
}],
selectedRole: {
id: '1',
name: 'Apple'
} //This sets the default value of the select in the ui
};
Then assign the first array element to selectedrole containing the array of values(Apple Mango Orange Grapes).
If you want the default to be apple and the array is ordered:
array = [Apple, Mango, Orange, Grapes]
Your model needs to be set to selectedRole:
data-ng-model="selectedRole"
In your controller, set:
selectedRole = array[0]
angular will take care of the rest of the data manipulation.
I hope this helps. Please provide more information for a clearer answer
Thanks
Handling a select element i.e. a drop down list in AngularJS is pretty simple.
Things you need to know is that you bind it to an array or a collection to generate the set of option tags using the ng-options or the ng-repeat directives which is bound to the data source on your $scope and you have a selected option which you need to retrieve as it is the one the user selects, it can be done using the ng-model directive.
If you want to set the selected option on the page load event, then you have to set the appropriate object or value (here it is the fruit id) which you are retrieving from data binding using the as clause in the ng-options directive as shown in the below embedded code snippet
ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
or set it to the value of the value attribute when using the ng-repeat directive on the option tag i.e. set data.model to the appropriate option.value
<select size="6" name="ngvalueselect" ng-model="data.model" multiple>
<option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
</select>
angular
.module('fruits', [])
.controller('FruitController', FruitController);
function FruitController() {
var vm = this;
var fruitInfo = getFruits();
vm.fruits = fruitInfo.fruits;
vm.selectedFruitId = fruitInfo.selectedFruitId;
vm.onFruitChanged = onFruitChanged;
function getFruits() {
// get fruits and selectedFruitId from api here
var fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Mango' },
{ id: 3, name: 'Banana' },
{ id: 4, name: 'Orange' }
];
var fruitInfo = {
fruits: fruits,
selectedFruitId: 1
};
return fruitInfo;
}
function onFruitChanged(fruitId) {
// do something when fruit changes
console.log(fruitId);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fruits">
<div ng-controller="FruitController as ctrl">
<select ng-options="fruit.id as fruit.name for fruit in ctrl.fruits"
ng-model="ctrl.selectedFruitId"
ng-change="ctrl.onFruitChanged(ctrl.selectedFruitId)">
<option value="">Select Fruit</option>
</select>
</div>
</div>
Check the Example section here for more information.
I have a select box which is populated with some data from my controller. When an input value changes the contents of the select box should be filtered and a default value should be assigned based on the is default property of the data object.
Is there any way this can be done using angular directives or would it need to be done as a custom filter function doing something along the lines of
angular.forEach(vm.data,function(item){
if (vm.q == item.someId && item.isDefault) {
vm.result = item.value;
}
});
My html looks something like
<div ng-app="myApp" ng-controller="ctrl as vm">
<input type="text" ng-model="vm.q">
<select ng-options="item.value as item.description for item in vm.data | filter:{someId:vm.q}" ng-model="vm.result"></select>
</div>
and my controller looks like:
(function(){
angular.module('myApp',[]);
angular
.module('myApp')
.controller('ctrl',ctrl);
function ctrl()
{
var vm = this;
vm.data = [
{
someId: '1',
description: 'test1',
value: 100,
isDefault: true
},
{
someId: '2',
description: 'test2',
value: 200,
isDefault: false
},
{
someId: '3',
description: 'test3',
value: 100,
isDefault: true
},
];
}
})();
See my plunkr demo here: http://plnkr.co/edit/RDhQWQcHFMQJvwOyHI4r?p=preview
Desired behaviour:
1) Enter 1 into text box
2) List should be filtered to 2 items
3) Select box should pre-select item 1 based on property isDefault set to true
Thanks in advance
I'd suggest you include some 3rd party library, like lodash, into your project to make working with arrays/collections that much easier.
After that you could add ng-change directive for your input.
<input type="text" ng-model="vm.q" ng-change="vm.onChange(vm.q)">
And the actual onChange function in the controller
vm.onChange = function(id) {
var item = _.findWhere(vm.data, { someId: id, isDefault: true });
vm.result = item ? item.value : null;
};
And there you have it.
I have created an application in AngularJS with a drop down with space in option using a filter. The application is working fine with the options in drop down with indentation space before the values but the problem is when a select an option which is having a space, the space is also shown in the view like as shown below
actually I want the indentation space within the drop-down options but only thing is that I don't want that space to be get displayed when selection shown above
can anyone please tell me some solution to prevent the space to display when selection
My code is as given below
JSFiddle
<select>
<option ng-repeat="(key, value) in headers">{{value | space}}
</option>
</select>
<select ng-model="selectedValue" ng-change="selVal = selectedValue.trim(); selectedValue=selVal">
<option ng-if="selVal">{{selVal}}</option>
<option ng-repeat="(key, value) in headers" ng-if="selVal != value.value">
{{value | space}}
</option>
</select>
This is as close as it gets without jquery, temporarily changing the view state of the option when it's chosen. If that doesn't satisfy you and you still want it to be shown indented when the dropdown menu is open, check out this question on how to detect the state of the select component and update the display function accordingly. Alternatively, you can create your own select directive and manage the details within that, but I doubt that's worth the trouble if you're not using it in many places.
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.headers = [{
value: 'value 1'
}, {
value: 'value 2',
mainId: 12
}, {
value: 'value 3'
}, {
value: 'value 4',
mainId: 14
}, {
value: 'value 5'
}, {
value: 'value 6',
mainId: 18
}];
$scope.chosen = $scope.headers[0].value;
$scope.display = function(header) {
var chosenObject = _.find($scope.headers, {value: $scope.chosen});
if (!_.isUndefined(header.mainId) && header !== chosenObject) {
return '\u00A0\u00A0' + header.value;
} else {
return header.value;
}
}
});
HTML here:
<div ng-app='myApp' ng-controller="ArrayController">
<br></br>
SELECT:
<select ng-model="chosen" ng-options="header.value as display(header) for header in headers">
</select>
</div>
There's yet another alternative with CSS and ng-class, fiddle here:
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.headers = [{
value: 'value 1'
}, {
value: 'value 2',
mainId: 12
}, {
value: 'value 3'
}, {
value: 'value 4',
mainId: 14
}, {
value: 'value 5'
}, {
value: 'value 6',
mainId: 18
}];
$scope.chosen = $scope.headers[0].value;
$scope.isIndented = function(header) {
var chosenObject = _.find($scope.headers, {value: header});
return !_.isUndefined(chosenObject.mainId);
};
});
app.filter('space', function() {
return function(text) {
if(_.isUndefined(text.mainId))
{
console.log('entered mainId');
return text.value;
}
else
{
console.log('entered');
return '\u00A0\u00A0' + text.value;
}
};
});
HTML:
<div ng-app='myApp' ng-controller="ArrayController">
<br></br>
SELECT:
<select ng-model="chosen" ng-options="header.value as (header | space) for header in headers" ng-class="{'indented-value': isIndented(chosen)}">
</select>
</div>
CSS:
.indented-value {
text-indent: -9px;
}
First off, this was a great question. I've unfortunately spent way too much time trying to come up with a solution to this. I've tried everything from CSS, to using ngModelController $formatters, to the solution (which isn't optimal as you'll see) I've posted below. Note, I do not think my solution deserves to be selected as the answer. It just "sorta" works, but like other solutions, it has a fatal flaw.
However, since your question was:
can anyone please tell me some solution to prevent the space to
display when selection
My official answer is:
No
There is no cross-browser way to get this working. No amount of CSS, jQuery, or Angular magic will make this work. While it may be disappointing, I think that is going to be the only correct answer to your question.
No one is going to be able to give you a solution that prevents the space from being displayed in the select box while maintaining it in the options that works reliably across browsers. Chrome and Firefox allow some amount of styling of elements in the select, options, and optgroup family, but nothing is consistent and works everywhere.
My best run at it is in this Plunk
It uses the fact that optgroup will do indentations for you, but it comes with terrible differences in how different browsers handle it. With some you can style away the problem, but others do not work (and never will). I'm posting it so maybe someone will be inspired and figure out a way to prove me wrong.
<body ng-app="app">
<div ng-app='myApp' ng-controller="ArrayController">
<div>{{selectedValue}}</div>
SELECT:
<select ng-model="selectedValue" >
<option indented="item.mainId" ng-repeat="item in headers">{{item.value}}</option>
</select>
</div>
</body>
(function() {
var app = angular.module('app', []);
app.controller('ArrayController', function($scope, $timeout) {
$scope.headers = [{
value: 'value 1'
}, {
value: 'value 2',
mainId: 12
}, {
value: 'value 3'
}, {
value: 'value 4',
mainId: 14
}, {
value: 'value 5'
}, {
value: 'value 6',
mainId: 18
}];
});
app.directive('indented', function($parse) {
return {
link:function(scope, element, attr){
if($parse(attr.indented)(scope)) {
var opt = angular.element('<optgroup></optgroup>');
element.after(opt).detach();
opt.append(element);
}
}
};
});
})();
If you opened the question up and allowed the implementation of a directive that mimicked the behavior of select but was instead built with li elements, then this would be trivial. But you simply can't do it with select.
Given your code, you can add one helper directive, to remove space in link function, once your option got selected.
As an example, add an id to your select, and directive
<select id="mySelect" option-without-space>
<option ng-repeat="(key, value) in headers">{{value | space}}
</option>
</select>
And directive might look like,
app.directive('optionWithoutSpace', () => {
return {
restrict: 'A',
link: function(scope, elem, attributes) {
var selectedOptionWithoutSpace = function () {
var selectedOption = $('#mySelect option:selected');
var optionText = selectedOption.text();
selectedOption.text(optionText.trim())
return false;
};
$(elem).on('change', selectedOptionWithoutSpace);
}
}
})
This is with a little help of jQuery, but I assume it is not a big problem.
Here is a fiddle.
Try this...
Change select box html following
<select ng-model="selectedOption" ng-options="item.value for item in headers"></select>
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.headers = [{
value: 'value 1'
}, {
value:'value 2',
mainId: 12
}, {
value: 'value 3'
}, {
value: 'value 4',
mainId: 14
}, {
value: 'value 5'
}, {
value: 'value 6',
mainId: 18
}];
$scope.selectedOption = $scope.headers[0]; //Add this line
});
app.filter('space', function() {
return function(text) {
if(_.isUndefined(text.mainId))
{
console.log('entered mainId');
return text.value;
}
else
{
console.log('entered');
return '\u00A0\u00A0' + text.value;
}
};
});
I have an add button that uses a directive to add-to a table's (.estimates) tbody:
function EstimateCtrl( $scope, $compile ) {
$scope.services = [
{ 'value': 'c', 'name': 'Standard Courier' },
{ 'value': 'xc', 'name': 'Express Courier' },
{ 'value': 'cc', 'name': 'Country Courier' }
]
$scope.add = function() {
angular.element('.estimates tbody').append( $compile('<tr estimate></tr>')($scope) );
}
}
angular.module('dashboard', [])
.directive('estimate', function() {
return {
restrict: 'A',
template: '<td><input type="text" placeholder="Suburb"/></td><td><select ng-model="estimate.service" ng-options="service.value as service.name for service in services" class="form-control"></select></td><td>$0.00</td><td><button type="button" class="remove">x</button></td>',
link: function( scope, element, attrs ) {
element.find('.remove').bind('click', function() {
element.closest('tr').remove();
});
}
}
});
How can I have an element array using ng-model in angularjs? For example:
<select name="foo[]"></select>
to
<select ng-model="foo[]"></select>
I've been digging around for a day and half but I can't seem to catch a break. I was hoping that maybe someone can point me in the right direction. Thank you very much for any help.
Edit: Here is the link to the plunker I'm sure after seeing this everyone is going know what I'm on about:
http://plnkr.co/edit/JlYB9P0vyAqghOmeNYh4
Edit2: Let's see if I can give you all another example to show you what I'm after
<form method="POST" action="">
<!-- I was attempting to do ng-model="estimate.service[]" but of course this doesn't work -->
<select name="estimate[service][]">
<option value="foor">Foo</option>
<option value="bar">Bar</option>
</select>
<select name="estimate[service][]">
<option value="foor">Foo</option>
<option value="bar">Bar</option>
</select>
<select name="estimate[service][]">
<option value="foor">Foo</option>
<option value="bar">Bar</option>
</select>
<input type="submit" value="Submit"/>
</form>
<?php
if ( $_POST )
{
print_r( $_POST['estimate']['service'] );
}
?>
Output
Ohrighty! I managed to find a work around.
I have abandoned directives and did it another way, here is my working code:
HTML:
<div ng-controller="Ctrl">
<table>
<tbody ng-repeat="service in estimate.services">
<tr>
<td><input type="text" placeholder="Suburb"/></td>
<td>
<select ng-model="estimate.services[service.name]" ng-options="option.value as option.name for option in options" class="form-control"></select>
</td>
<td>$0.00</td>
<td><button type="button" class="remove">x</button></td>
</tr>
</tbody>
</table>
</div>
JavaScript:
function Ctrl( $scope, $compile ) {
$scope.estimate.services = [
{ name: 'service1', value: '' }
];
$scope.options = [
{ name: 'Option 1', value: 'opt1' },
{ name: 'Option 2', value: 'opt2' },
{ name: 'Option 3', value: 'opt3' }
];
$scope.add = function() {
$scope.estimate.services.push({
name: 'service' + ($scope.estimate.services.length + 1),
value: ''
});
};
}
EDITED:
Ok lets say you have two arrays of configurable options:
options1=[...]
options2=[...]
Now if I understand correctly you want a select box that enables yout to select one set of them right? So first you need to enclose both of them in another array or as mentioned before another object.
So lets use an object (I can provide an array example as well)
var $scope.myOptions ={'LabelForOptions1' : options1, 'LabelForOptions2' : options2}
Next we need a place to store the options that were choosen
$scope.selectedOptions = {};
and lastly the select box itself
<select ng-model="selectedOptions" ng-options="value as key for (key,value) in myOptions"></select>
Note that the options1 and options2 variable could be also a single value and the example would still work
COMPLETE SOLUTION TO PROBLEM:
I assume this is your model:
function MyController($scope) {
$scope.options1 = ['Foo1','Bar1'];
$scope.options2 = ['Foo2','Bar2'];
$scope.options3 = ['Foo3','Bar3'];
$scope.allOptions = [$scope.options1, $scope.options2, $scope.options3];
$scope.selectedOptions = ["none","none","none"];
};
So this would be the solution:
<!DOCTYPE html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="./js/myAngular.js"></script>
</head>
<body ng-controller="MyController">
<div><select ng-repeat="option_set in allOptions"ng-model="selectedOptions[$index]" ng-options="value for value in option_set">
</select></div>
</body>
</html>
Working example:
http://jsfiddle.net/qGRQF/11/