Filter select options in angularjs - javascript

In my Angularjs application, i am having code as follows,
HTML:
<div ng-app="test" ng-controller="test">
<div>
<input type="checkbox" ng-model="showvalidrates"> Display only Valid Rates
<br><br>
<select ng-model="selectRate"
ng-options="option.id as option.name for option in data">
</select>
</div>
</div>
JS:
angular.module('test', [])
.controller('test', ['$scope', function ($scope) {
$scope.data = [
{name: 'Rate 1', id: 1, valid: true},
{name: 'Rate 2', id: 2, valid: false},
{name: 'Rate 3', id: 3, valid: true}
];
$scope.selectRate = $scope.data[1].id;
$scope.showvalidrates = true;
}]);
Here i am making ng-options to display the rates, and i am having a checkbox which will be in checked state by default.
In this scenario, i am in the need to filter the ng-options to display only the valid rates for which i am having a property called valid: true or valid: false.
Here if the checkbox is checked which means showvalidrates is true, then only the object with valid: true needs to be displayed in options.. But if the value is selected already, In the working example given below {name: 'Rate 2', id: 2, valid: false} is selected but it has valid: false in this case the selected value needs to be displayed (means Rate 2 only needs to be in selected state). unless user touches the select box, but if he clicks the select box then only valid rates needs to be displayed and he can select any of the valid rates.
And if he uncheck the showvalidrates (false) then all the rates needs to be displayed in ng-options ..
JsFiddle: http://jsfiddle.net/opygzs4a/
As per example given,
showvalidrates = true
Options:
Rate 1
Rate 2 (Selected)
Rate 3
Onclick on the select box only Rate 1 and Rate 3 needs to displayed and user can select any of these two.
Unless any of these two were chosen the Rate 2 alone needs to be in selected state and selectRate should have the value as 2 only.
The valid property was the newly implemented in code to filter the data, so in order to affect the earlier selectRate value in the application, this scenario needs to be implemented.(Even if valid is false let it be selected unless user changes)..
I am very new in AngularJs and this scenario, so please help me how to handle this situation..
If there is any alternative approach for it it would be also welcomed but requirement is the same as like mentioned above.

To achieve expected result , use below option of using filter with checkbox condition
ng-options="option.id as option.name for option in data|filter: !init && showvalidrates?{valid:true}:{}" ng-init="init = true">
On check, showvalidrates is true and based on that set filter as { valid: true } to display options with flag valid -true
On uncheck, showvalidrates is false and based on that set filter as {}
Add ng-init flag to control initial default value
Codepen - https://codepen.io/nagasai/pen/GbrOMm?editors=1010
working code sample
angular.module('test', [])
.controller('test', ['$scope', function ($scope) {
$scope.data = [
{name: 'Rate 1', id: 1, valid: true},
{name: 'Rate 2', id: 2, valid: false},
{name: 'Rate 3', id: 3, valid: true}
];
$scope.selectRate = $scope.data[1].id;
$scope.showvalidrates = true;
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="test" ng-controller="test">
<div>
<input type="checkbox" ng-model="showvalidrates" ng-change="init = false"> Display only Valid Rates
<br><br>
<select ng-model="selectRate"
ng-options="option.id as option.name for option in data|filter: !init && showvalidrates?{valid:true}:{}" ng-init="init = true" ng-click="init = false">
</select>
</div>
</div>

Related

Handling dropdown in angular js

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.

How to display the selected value in select option field from the json object fetched form server angularjs

I have fetched a json object with the list of countries. And now i want to display the selected name of the country in the select option box. I've tried different ways but there always keep showing the blank value.
Note:countries is the json object having the list of countries with key value pair. It used to display the select option in the view. And tabs[0].data.country is the value of country id which is to be selected.
Some of the codes i have tried:
Code to display the selected country name:
Code to display the select option in View:
Output:
Convert you json object into an array of objects first, and then you do something like
<select name="countries" id="contries" ng-model="vm.country">
<option ng-repeat="country in vm.countries" value="{{country.id}}">{{country.name}}</option>
</select>
Just loop over them and pick what you want from the list. Full documentation here: https://docs.angularjs.org/api/ng/directive/select
Well finally, here is the snippet that solved my problem.
html
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption">
</select>
</form>
</div>
js
angular.module('defaultValueSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
],
selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
};
}]);
For more information you can go to this link
Also another useful tutorial here

Angular filter expression

I'm working on a filter expression that filters by the data-ID of an element.
The problem I'm having is that the filter will return multiple values if other ID's have the same digits positioned elsewhere (i.e. filter 12 RETURNS 12, 123, 1234). I'd like to just return the one element with the exact value of 12.
JS
angular.module('app', []).controller('TestCtrl', function($scope) {
$scope.customers = [
{
id: 12,
name: 'customer 1 - 1'
},
{
id: 123,
name: 'customer 2 - 12'
},
{
id: 1234,
name: 'customer 3 - 12'
}
];
});
HTML
Filter: <input ng-model="filterCustomer" />
<hr/>
<select size="4" ng-options="customer as customer.name for customer in customers | filter:{id: filterCustomer} track by customer.id" ng-model="customerSelection">
</select>
I've also tried adding the following expression to the filter to match digit length... but it's not working as expected
filter:{id:filterFsaisCustomer.toString().length}
Here is a Plunker.
It should be used as strict checking by adding true inside your filter, also you should have convert the value in integer just by making input field to type="number" will parse that to int.
Markup
<input type="number" ng-model="filterCustomer" />
<select size="4"
ng-options="customer as customer.name for customer in customers | filter:{id: filterCustomer}:true track by customer.id"
ng-model="customerSelection">
</select>
Working Plunkr
Edit
To enable filter only after value entered in textbox then it would become conditional base strict checking | filter:{id: filterCustomer}:filterCustomer>0
<select size="4"
ng-options="customer as customer.name for customer in customers | filter:{id: filterCustomer}:filterCustomer>0 track by customer.id"
ng-model="customerSelection">
</select>
Updated Plunkr

Angular change default value of select from filter

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.

hide input values based on selected option in dropdown, ng-repeat ng-hide

Without JQuery I'd like to be able to hide certain form input fields when a selection is made in the <select> drop down menu.
Similar to this behavior, but with ng-repeat. And a little more dynamic, making ng-hide use some sort of isHidden function calling the ng.models attributes, comparing to the selected value
Here's my attempt: http://jsfiddle.net/Td2NZ/260/, with the ng-hide being ng-hide="address.state === 'FL'"
the === FL part is hardcoding "FL", but I'd like that to draw from the input that is being repeated in ng-repeat.
Fiddle: http://jsfiddle.net/Td2NZ/261/
A couple things to note: the way to determine if something is hidden should be a property of the input to be hidden, not the select menu option. You had an attribute in the drop down affects: xxx, now that is an attribute of the input: hiddenBy: xxx. Also to hide the label as well the ng-hide has been moved to the <div> tag. This should get you started. Another resource that helped solve this problem was http://plnkr.co/edit/SxIvt4KThWLtWvh3PnOh?p=preview
The JSFiddle you provided almost works, if you want it to work with hardcoded "FL" change === to ==.
=== checks type and value, where you really want to just check value is equal. It is best practice to always use ===, but in this scenario you should use ==.
angular
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.addresses = [
{'state': 'AL'},
{'state': 'CA'},
{'state': 'FL'}
];
$scope.lov_state = [
{'lookupCode': 'AL', 'description': 'Alabama'},
{'lookupCode': 'FL', 'description': 'Florida'},
{'lookupCode': 'CA', 'description': 'California'},
{'lookupCode': 'DE', 'description': 'Delaware', 'affects': 'hidden'}
];
$scope.inputs_text = [
{label: "Start Date", input:'yyyy-mm-dd', name:'dat_start', isRequired: "true"},
{label: "End Date", input:'yyyy-mm-dd', name:'dat_end', isRequired: "true"},
{label: "hide_for_FL", input:'wow', name:'hidden', isRequired: "true", hiddenBy: 'FL'}
];
$scope.isHidden = function(){
return message = (address.state === 'FL');
};
});
html
<div ng-controller="MyCtrl">
<div>Billing State:
<select ng-model="address.state" ng-options="state.lookupCode as state.description for state in lov_state" ng-init="address.state=1"></select>
<p> address.state: {{address.state}}</p>
</div>
<br> <tt>State selected: {{address.state}}</tt>
<div ng-repeat="input in inputs_text" ng-hide="(input.hiddenBy == address.state)">
<label>{{input.label}}</label>
<input name="{{input.name}}" id="{{input.name}}" ng-model="input.input" ng-require="input.isRequired"></input> <!-- function -- find address.state in the array, when match found get affects option and if it equals input.input return true -->
<p> Input: {{input.input}}</p>
</div>
</div>

Categories

Resources