Angularjs - get selected item text of select without ng-option - angularjs

I have a dropdownlist -
<select ng-model="contact.type" id="select_{{$index}}" ng-change="changedValue()" class="searchCriteria">
<option>Policy Number</option>
<option>Insured Name</option>
</select>
I want to get the selected item using angularjs. So far I have tried
$scope.changedValue = function () {
alert($(".searchCriteria option:selected").html());
}
among other things. But each time the alert shows "undefined". How do I get the selected option text?

You can just use the $scope variable,
$scope.changedValue = function () {
alert($scope.contact.type);
}

Related

Angularjs select2 set options selected

I want to build select list (select2) options when user clicks on html button.
My HTML:
<select id="mySel2" class="form-control" multiple="multiple">
<option ng-repeat="item in items" ng-selected="item.selected"
ng-model="item.tag">
{{item.tag}}
</option>
</select>
Angular js function code on button click:
var fruits=angular.module("myApp",[]);
fruits.controller('ctrlTags', function($scope){
/* I HAVE SET DEFAULT VALUE TO SELECT LIST*/
/* IT WORKING PERFECT WITH SHOWING SELECTED VALUES*/
var tagsData = [
{id:1,tag:'Apple'},
{id:2,tag:'Banana'},
{id:3,tag:'Cherry'},
{id:4,tag:'Cantelope'},
{id:5,tag:'Grapefruit'},
{id:6,tag:'Grapes',selected:true},
{id:7,tag:'Lemon'},
{id:8,tag:'Lime'},
{id:9,tag:'Melon',selected:true},
{id:10,tag:'Orange'},
{id:11,tag:'Strawberry'},
{id:11,tag:'Watermelon'}
];
$scope.items = tagsData;
/*NOW ON BUTTON CLICK GETKEY() FUNCTION WILL BE CALLED*/
/* AND I WANT TO RENDER/REFRESH SELECT LIST WITH NEW DATA */
$scope.getKey=function(data){
var newData = [
{id:4,tag:'car'},
{id:5,tag:'bat',selected:true},
{id:6,tag:'cat',selected:true},
{id:7,tag:'Lemon'},
{id:8,tag:'Lime'},
];
$scope.items=newData;
};
});
ISSUE:ON BUTTON CLICK IT IS UPDATING SELECT LIST VALUES BUT NOT SHOWING DEFAULT SELECTED VALUES
PLEASE TELL ME HOW TO REFRESH SELECTED VALUE AS WELL.
Use select2 (form-widgets.js)
$('[name="NAME"]').select2({placeholder: ''}).val(VAL).change();
You need to add model into select section ng-model="selected".
You can add for example first index
in controller $scope.selected = tagsData[0]

Remove Option dynamically From select box

api return status which is assign to $scope.status it come dynamically
$scope.status = [{"planStatus":"Completed","records":2},{"planStatus":"Partial","records":22},{"planStatus":"Active","records":24},{"planStatus":"Merged","records":6}]
This is my html code where i created select box using ng-repeat
<select ng-options="sta.planStatus as sta.planStatus for sta in status" ng-model="plan.planStatus" class="form-control">
<option class="selectoption" value="">Select Status</option>
</select>
I am creating a select box, 5 option show in my select box
I want to remove one option(like Active) from html? How can i do it. it is possible to do without change api response
You can use angular filters to remove the options. To remove the option where planStatus is 'Active', try this.
ng-options="sta.planStatus as sta.planStatus for sta in status | filter: optionsFilter"
In Controller:
$scope.optionsFilter = function (option) {
if (option.planStatus == 'Active') {
return false;
}
return true;
}

Get selected option in ngOptions with protractor

How can I get the object associated to the selected option inside within a dropdown (select)?
Here's my html:
<select ng-model="selSeason" ng-options="season as season.name for season in seasons"></select>
Every season is an object with several properties and I'd need to get the object associated to the selected object (and not only its text or value).
I know ng-repeat has something like (to select name of the 5th season):
element(by.repeater('season in seasons').row(4).column('name'));
Is there something similar for by.options() selector?
Thanks
You can use by.options with evaluate():
var seasonNames = element.all(by.options('season in seasons')).evaluate("season.name");
seasonNames.then(function (values) {
console.log(values); // array of season names is printed
});
You can also filter out the selected option with filter():
var selectedSeasonName = element.all(by.options('season in seasons')).filter(function (option) {
return option.getAttribute("selected").then(function (selected) {
return selected;
});
}).first().evaluate("season.name");
selectedSeasonName.then(function (value) {
console.log(value); // selected season name is printed
});
What you are looking for is the custom by.selectedOption locator.
element(by.selectedOption('model_name'))
For a better description, read this: https://technpol.wordpress.com/2013/12/01/protractor-and-dropdowns-validation/
I ended up evaluating not the selected option but the ng-model associated to the select:
HTML
<select ng-model="selSeason" ng-options="season as season.name for season in seasons"></select>
JS
element(by.model('selSeason')).evaluate('selSeason').then(function(season){
console.log(season.name);
});
Your binding looks good, you can read all the properties easily by using your ng-model variable 'selSeason', see this example
<select ng-model="user"
ng-options="x as x.name for x in users track by x.id"
class="form-control"
ng-required="true">
<option value="">-- Choose User --</option>
</select>
var id = $scope.user.id;
var name = $scope.user.name;
var role = $scope.user.role
For more detail check this

I want to select each value in dropdown and it is coming dynamically to do unit testing using protractor

This is my select tag
<select id="selectPrimaryObject" class="form-control" ng-change="getPrimaryRelations()" ng-model="relation.from">
<option id="md-option" ng-repeat="item in primaryObjectsList" value="{{item.id}}">{{item.name}}</option>
</select>
And my protractor code is
element.all(by.id('selectPrimaryObject')).each(function (values, index) {
values.click(); // select the <select>
browser.driver.sleep(5000); // wait for the renderings to take effect
element.all(by.id('md-option')).click(); // select the first md-option
browser.driver.sleep(5000); // wait for the renderings to take effect
});
It is selecting last item from dropdown, but I want each item to be selected one by one.
Find the options by repeater, click every option with the help of each():
var selectElement = element(by.id('selectPrimaryObject'));
selectElement.click();
var options = selectElement.all(by.repeater('item in primaryObjectsList'));
options.each(function (option) {
option.click();
});

Angular UI Select2, why does ng-model get set as JSON string?

I'm using angular-ui's select2 for a fairly simple dropdown. It's backed by a static array of data sitting on my controller's scope. In my controller I have a function that gets called on ng-change of the dropdown so that I can perform some actions when the value changes.
However, what I'm finding is that the ng-model's property gets set as a JSON string rather than an actual javascript object, which makes it impossible to use dot notation to grab properties off of that model.
Here's the function that handles the value of the dropdown getting changed:
$scope.roleTypeChanged = function() {
//fine:
console.log('selectedType is: ', $scope.adminModel.selectedType);
// this ends up being undefined because $scope.adminModel.selectedType is a
// JSON string, rather than a js object:
console.log('selectedType.typeCode is: ', $scope.adminModel.selectedType.typeCode);
}
Here's a plunker of my full example: http://plnkr.co/edit/G39iZC4f7QH05VctY8zG
I've never seen a property that's bound to ng-model do this before, however I'm also fairly new to Angular so it's likely that I'm just doing something wrong here. I can certainly do something like $.parseJSON() to convert the JSON string back to an object, but I'd rather not unless I have to.
Thanks for any help!
You need to use ng-options on your select if you want to have object values. Actually creating the options yourself using an ng-repeat will only allow you to have string values for the various options:
<select ui-select2
ng-model="adminModel.selectedType"
ng-change="roleTypeChanged()"
data-placeholder="Select Role Type" ng-options="type.displayName for type in adminModel.roleTypes">
<option value=""></option>
</select>
http://plnkr.co/edit/UydBai3Iy9GQg6KphhN5?p=preview
Thanks Karl!
I have struggled a day with this
as a note for others having similar problems as I did,
when using an ng-model not accessible and defined in the controller/directive I solved it like this.
//country.Model has Code and Name nodes
* HTML *
<select
name="country" data-ng-model="country.Model"
data-ui-select2=""
data-ng-change="countryChanged(country.Model)" <!--only for test, log to console-->
data-ng-options="country as CodeAndName(country) for country in countries"
data-placeholder="{{placeholderText(country.Model, '- - Select Country - -')}}" >
<option value=""></option>
</select>
* JS *
function controller($scope, $q, $location, $routeParams) {
$scope.countryChanged = function(item) { // for test
console.log('selectedType is: ', item);
};
//returns the item or the text if no item is selected
$scope.placeholderText = function (item, text){
if (item == undefined)
return text;
return $scope.CodeAndName(item);
};
// returns a string for code and name of the item, used to set the placeholder text
$scope.CodeAndName = function (item) {
if (item == undefined)
return '';
return item.Code + ' - ' + item.Name;
};

Resources