How to get the selected value in select? - javascript

I am working on a angularjs form. I want to pass definition.clazz to a js function. In the controller, i have a js function like :
$scope.createData=function(clazz){
// do stuff
}
Here is the snippet of form :
<select class="form-control" id="type" name="type" ng-model="definition.clazz">
<option value="PrimitiveType"
ng-selected="type.type=='PRIMITIVE'">
PrimitiveType
</option>
<option value="EnumerationType"
ng-selected="type.type=='ENUM'">
EnumerationType
</option>
</select>
<button type="button"
class="btn btn-primary"
ng-click="createData(definition.clazz)">
Create Data
</button>
When I click to create Data button, the ng-model is not set. Even when I print definition.clazz in console log.
How to get the select value of select?
Thanks.

Have you tried using ng-options instead? My guess is that ng-model probably requires that on the select.

Try this:
<select class="form-control"
id="type"
name="type"
ng-model="definition.clazz"
ng-options="option in ['PrimitiveType','EnumerationType']">
</select>

#Pracede, is this the working solution that you want to achieve?
The value of ng-model is shown in console:
var app = angular.module("app", []).controller('appCtrl', ['$scope',
function($scope) {
//$scope.type ={type="PRIMITIVE"}; // the tricky part?
$scope.type = {};
$scope.type.type="";
$scope.createData = function(clazz) {
if(clazz==undefined)
{
console.log("SELECT THE TYPE");
return;
}
if(clazz=='PrimitiveType')
{
$scope.type.type='PRIMITIVE';
console.log(clazz + ' ' + $scope.type.type);
}
else
{
$scope.type.type='ENUM';
console.log(clazz + ' ' + $scope.type.type);
}
}
}
]);
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
</head>
<body ng-controller="appCtrl">
<select class="form-control" id="type" name="type" ng-model="definition.clazz">
<!--<option value="PrimitiveType" ng-selected="type.type=='PRIMITIVE'">PrimitiveType</option>
<option value="EnumerationType" ng-selected="type.type=='ENUM'">EnumerationType</option>-->
<option value="PrimitiveType">PrimitiveType</option>
<option value="EnumerationType">EnumerationType</option>
</select>
<button type="button" class="btn btn-primary" ng-click="createData(definition.clazz)">
Create Data
</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>
</html>
EDIT:
You can look these similar problems on SO:
How does ng-selected work?
Updating model with ng-options and ng-selected
but this is my understanding and one of solutions of your problem.
You can change the type with value inside the option and set the type depending on value in controller's function. So, there is no need to to use ng-selected (my opinion in this case).
I hope this addition will push you forward.

Related

adding option to select gets automatically selected

I have a dropdown which uses ng-options (angular).
I have a default option selected with an empty value. (so it has the "selected" attribute and same value as the model)
Whenever I add another element to the ng-options, which is not empty, if the model has an empty value (which is pointing to the default empty option), the new added option is automatically selected.
The value of the model is still empty, but the dropdown now shows the new added option automatically.
I've also tried to make the default option be " " instead of just "", but it still does the same change.
Any way to guarantee new added options are not automatically selected?
`<select class="form-control section" ng-model="action.prop">
<option value="" disabled selected>Select Property</option>
<option ng-repeat="prop in tr.props| orderBy:prop.name"
value="{{prop.name}}"> {{prop.name}} </option>
</select>`
Try this :)
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
</select>
<p>{{selectedName}}</p>
<button ng-click="add()">add</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = [""];
$scope.selectedName = $scope.names[0]
$scope.add = function() {
$scope.names.push("new");
}
});
</script>
</body>
</html>
You can simply just set your ng-model in the controller to the following before running your get dropdown function. This way it will always be set to default.
Controller
$scope.action = {};
$scope.action.prop = '';
Even though Roth's solution would work well in my case.
So would Nishant's if I used ng-options and a filter.
I decided instead, on the ng-repeat, to have an ng-if="prop.name != ''".
Since what was happening for me was that for about a second, ng-repeat would have latest prop with empty name for a second, and as ng-model = "", it was setting that option as selected.
<select class="form-control section" ng-model="action.prop">
<option value="" disabled selected>Select Property</option>
<option ng-if="prop.name != ''" ng-repeat="prop in tr.props| orderBy:prop.name"
value="{{prop.name}}"> {{prop.name}} </option>
</select>

AngularJS - Chosen ng-model is not working properly

I'm trying to get value when I select an option from an AngularJS chosen localytics dropdown.
Here's the code for the dropdown:
<select chosen style="width: 250px"
ng-model="StudentId"
ng-options="allStudent.StudentId as allStudent.Name for allStudent in allStudent">
<option value="">Select</option>
</select>
<h2>Chosen with static options: {{ StudentId }}</h2>
<input type="button" value="Search" ng-click="GetStdCourseList(StudentId)">
And in my controller I have the following function:
$scope.GetStdCourseList = function (StudentId) {
alert(StudentId);
};
When I use alert then it show me 'Undefined' instead of showing value
How can I solve this?
Actually this is ok and I get value when I'm not using chosen search but when I use 'chosen' then it's not working.... Here is the screenshot:
Thanks a lot.
I think you have not selected any options before clicking the button. This works fine for me when I select the option.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.allStudent = [{StudentId: 0, Name: 'name1'}, {StudentId: 1, Name: 'name2'}];
$scope.GetStdCourseList = function (StudentId) {
alert(StudentId);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select chosen style="width: 250px"
ng-model="StudentId"
ng-options="allStudent.StudentId as allStudent.Name for allStudent in allStudent">
<option value="">Select</option>
</select>
<h2>Chosen with static options: {{ StudentId }}</h2>
<input type="button" value="Search" ng-click="GetStdCourseList(StudentId)">
</div>
well, since ng-model's object is $scope.something itself, try to
replace
alert(StudentId)
become
alert($scope.StudentId)
and i don't think on this case you will need param. just ignore it because $scope covered it for you
that's will do
edited for better readability

ng click and/or ng change

Morning, here is what happens.
I made a dev, it was working fine, but only with firefox.
When i tested it with chrome...it wasn't working at all.
So, I have a select and I want to save the selected value to deal with it later.
Here is my angular:
if ($scope.dateTemp == "") {
$scope.displayNotification('error', "Empty date");
} else {
alert($scope.dateTemp);
//dateTemp treatment
}
AND
$scope.saveDate = function(dateMin){
alert(dateMin);
$scope.dateTemp=dateMin;
};
My view:
<p>Select date
<br/>
<select ng-model="date_selection" ng-change="saveDate(dateMin)">
<option ng-repeat="dateMin in listeDate" track by $index>{[{dateMin}]}</option>
</select>
</p>
When i tried this, i got undefined with my alert (btw saveDate function is just a setter for $scope.dateTemp)
Moreover when i try this, it works fine, but not with chrome.
<select ng-model="date_selection">
<option ng-click="saveDate(dateMin)" ng-repeat="dateMin in listeDate" track by $index>{[{dateMin}]}</option>
</select>
Thanks for your advice.
You can also use ng-options inside select tag
Controller :
app.controller('MainCtrl', function($scope) {
$scope.listeDate = [{"value":1,"text":"date1"},
{"value":2,"text":"date2"},
{"value":3,"text":"date3"},
{"value":4,"text":"date4"}];
$scope.Print=function(){
alert($scope.selected);
}
});
HTML:
<body ng-controller="MainCtrl">
<select ng-options="date.value as date.text for date in listeDate" ng-model="selected" ng-change="Print()"></select>
</body>
Working plunker link
track by $index should be included in the ng-repeat directive.
<select ng-model="date_selection" ng-change="saveDate(dateMin)">
<option ng-repeat="dateMin in listeDate track by $index">{[{dateMin}]}</option>
</select>
track by is an option of ng-repeat directive which helps to identify unique every item in the array.
Short example:
function TodoCtrl($scope) {
$scope.date_selection;
$scope.listeDate = ['date1','date2'];
$scope.saveDate=function(date_selection){
console.log(date_selection);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<select ng-model="date_selection" ng-change="saveDate(date_selection)">
<option ng-repeat="dateMin in listeDate">{{dateMin}}</option>
</select>
{{date_selection}}
</div>
</div>
I test it and it works in chrome and mozilla.

Select in Angular JS - I need the element and value attribute to be the same

I have a json like this, stored in $scope.result:
{ "tips":["p1","p2","p3","p4"],"actualTip":"p4"}
And I need to do a comboBox with Angular. I did this:
<select class="form-control" id="one" ng-model="actualTip" ng-options="tips for tips in result.tips" ></select>
And its puts me a combobox like this:
<option value="0"> p1 </option>
<option value="1"> p2 </option>
<option value="2"> p3 </option>
I need that the text and value of the option have the same "value".
For ex:
<option value="p1"> p1 </option>
<option value="p2"> p2 </option>
Edit: I forgot to say that I need the combobox starts with the option selected that is in "actualTip"
How can I do this?
Here is a snippet: http://codepen.io/rmadhuram/pen/leukx
Don't worry about the value Angular stores in the options. You will get the correct value you want in the scope variable (you can see that in the console).
Also, you just have to initialize the scope variable with the value you want.
JavaScript:
angular.module('app', [])
.controller('testCtrl', ['$scope', function($scope) {
$scope.result = { "tips":["p1","p2","p3","p4"],"actualTip":"p4"};
$scope.onSelect = function() {
console.log('selected: ' + $scope.actualTip);
};
$scope.actualTip = "p4";
}]);
HTML:
<div ng-app="app">
<div ng-controller="testCtrl">
<select class="form-control" id="one" ng-model="actualTip" ng-change="onSelect()" ng-options="tips for tips in result.tips" ></select>
</div>
</div>

Can't display selected value using select2

I'm using angular-ui's select2 directive. In terms of functionality it's working fine (after some hair pulling) but I just realized that what I did to make it work is now preventing select2 from displaying the selected value.
<select
ui-select2
id="entityDropDown"
ng-model="selectedUser"
ng-value="users[selectedUser].name"
ng-change="getUserInfo(users[selectedUser])">
<option></option>
<option ng-repeat="user in users" ng-value="{{$index}}" value="{{user.name}}">{{user.name}}</option>
</select>
At first I was using ngOptions, but it isn't compatible with Select2 so I had to use ngRepeat. My ngRepeat needs to send the selected user Object to a function on change. To accomplish this I had to use ng-value or value to bind the selected user $index to the select elements ng-modal selectedUser from there I could look up the object in users based on the index. BUUUT, now that's I've given my options the $index, the value returned to select2 doesn't make sense I guess and it's just giving me my place holder.
.run(['uiSelect2Config', function(uiSelect2Config) {
uiSelect2Config.placeholder = "Click here";
uiSelect2Config.dropdownAutoWidth = true;
}]);
I tried giving the select element it's own ng-value to kind of do what the ngChange was doing and look up the selected users name....but yea that didn't work out.
Actually you could leverage jQuery to fetch the selected option index when the 'entity drop down' has been changed. The example below is a simple demo for your question.
HTML
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>angular ui - select2</title>
<link rel="stylesheet" href="js/select2/select2.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div ng-controller="select2Ctrl">
<select id="entityDropDown" ui-select2 ng-model="selectedUser" data-placeholder="Select a user" ng-change="getUserInfo()">
<option value=""></option>
<option ng-repeat="user in users" value="{{user.name}}">{{user.name}}</option>
</select> VALUE: {{selectedUser}}
<br/><br/>
Selected User info:<br/><br/>
name:
{{selectedUserData.name}}<br/>
id:
{{selectedUserData.id}}
</div>
<script src="js/select2/select2.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<script src="js/angular-ui-select2/src/select2.js"></script>
<script src="js/angularUISelect2.js"></script>
</body>
</html>
Controller
angular.module("myApp",['ui.select2'])
.controller("select2Ctrl",function($scope){
$scope.selectedUser = "";
$scope.selectedUserData = {};
$scope.users = [{id:1,name:"user1"},{id:2,name:"user2"}];
$scope.getUserInfo = function(){
$scope.selectedUserData = $scope.users[jQuery("#entityDropDown")[0].selectedIndex-1];
};
});
ScreenShot
(1) before selection
(2) selecting
(3) after selection
Hope this is helpful.
Try rewriting the html to this:
<select
ui-select2
id="entityDropDown"
ng-model="selectedUser"
ng-change="getUserInfo(users[selectedUser])">
<option></option>
<option ng-repeat="user in users" ng-value="$index">{{user.name}}</option>
</select>
Notice that I removed ng-value from the select and the value attribute from the options (I also removed the {{..}} surrounding the $index)
selectedUser should always be an integer that represents an index in the users array

Categories

Resources