I am using angular js select to display the name which is of type json array.using the below code i could display the name when a name is selected it stores a json object which moves to the next page but when i come back to the select page i would like to show the previous selected name but it shows an empty field;
Html:
<select class="formSelect"
ng-model="vm.product.farmer"
ng-change="vm.fillStarted()"
ng-options="farmer as farmer.name for farmer in vm.load.selectedFarmers">
<option value="" selected hidden />
</select>
Ctrl:
vm.load.selectedFarmers = getFarmers();
function getFarmers () {
farmers = [
{ name: 'Nidhin', id: 22 },
{ name: 'Sathish', id: 10 },
{ name: 'Kumar', id: 23 },
{ name: 'Rajkumar', id: 24 }
];
return farmers;
}
when moving from first page to the second page the select has an object like {name: 'Nidhin', id: 22 }
While coming back from the second page to the first page how can i show the selected name?
You can check the position of your selected data based on the position you can change the ng-model value
if (CommonService.isValid(vm.product.farmer)) {
vm.currentPosition = vm.load.selectedFarmers.findIndex(function (item) {
return item.id === vm.product.farmer.id;
});
} else {
vm.currentPosition = -1;
}
vm.product.farmer = vm.load.selectedFarmers[vm.currentPosition];
Try the above code and check whether it solves your problem.
Related
I have some code below that displays two selects. The Name Select is filtered based on the option selected in the Tag Select.
This is all fine, however, I would like to keep a default option in the Name Select even after a tag has been selected.
Something like "Please Select" as the first option regardless of what is chosen in the Tags Select. - I still want the current functionality to remain so after clicking the Tags Select it will still show options in the Names Select based on what is Selected in the Tags Select.
Basically it will function as it does now but have a default option as the first option for names.
UPDATE: code below has been updated with the answer #CharlesEF provided, and it works for the first part of this question. However, since the answer was provided in a reply I could not mark as correct.
I've included updated code with an additional problem below. I need the price output to revert to null or a default value if the default Name or Tag option "please select" is selected.
With the current code, price output stays current with the previously selected name when the "please select" option is selected for Name or Tag.
let result = [{
name: "some name",
tag: "some tag",
price: "50"
},
{
name: "some name1",
tag: "some tag1",
price: "10"
},
{
name: "some name1-2",
tag: "some tag1",
price: "20"
},
{
name: "some name2",
tag: "some tag2",
price: "30"
},
{
name: "some name2-2",
tag: "some tag2",
price: "40"
}
];
//Generic function to fill a dropdown with options
let populateDropDown = (params) => {
let set = new Set()
params.optionsToPopulate.forEach(item => {
const txt = item[params.text];
if (!set.has(txt)) {
params.element.add(new Option(txt, txt))
set.add(txt);
}
})
}
//Initialize tags dropdown
(function() {
document.getElementById("tags").addEventListener('change', (event) => {
tagChanged(event);
});
let params = {
optionsToPopulate: result,
element: document.getElementById("tags"),
id: "tag",
text: "tag"
}
populateDropDown(params);
})();
//Tags dropdown change event.
let tagChanged = (event) => {
let tagValue = event.target.value;
//filter the results based on the value of tags dropdown
let optionsToAdd = result.filter(item => item.tag === tagValue);
let names = document.getElementById("names");
names.options.length = 1;
let params = {
optionsToPopulate: optionsToAdd,
element: names,
id: "name",
text: "name"
}
populateDropDown(params);
}
//Function to place price in span
let populatePrice = (params) => {
params.priceToPopulate.forEach((item) => {
params.spanElement.innerHTML =
(item[`${params.text}`], item[`${params.text}`]);
});
};
//Initialize price span
(function () {
names.addEventListener("change", (event) => {
nameChanged(event);
});
})();
//Names dropdown change event.
let nameChanged = (event) => {
let nameValue = event.target.value;
//Filter URL results based on the value of names dropdown
let priceToAdd = result.filter((item) => item.name === nameValue);
let priceSpan = document.getElementById("price");
let params = {
priceToPopulate: priceToAdd,
spanElement: priceSpan,
id: "price",
text: "price",
};
populatePrice(params);
};
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Tags:
<select id="tags">
<option value="please select">please select</option>
</select>
<br><br><br> Names:
<select id="names">
<option value="please select">please select</option>
</select>
<br><br><br> Price:
<span id="price"></span>
</body>
</html>
1st option
Hard code the default 1st option in the HTML markup, then use 'names.options.length = 1;'. This will keep the default 1st option.
2nd option
Add the default 1st option in Javascript, before the loop to fill in names.
Your span needs to be cleared with javascript. Just add 1 line of code, 'document.getElementById("price").innerHTML = "";'. You can put this line in the 'tagChanged' function or in the function that populates the dropdown.
EDIT:
If you want to clear 'price' when the 1st option is selected then you need to add an if test in the 'tagChanged' function. Test if the option value equals the value of the default 1st option. If yes, clear the span.
Glad this helped.
You can store the default value with a specific tag :
let result = [{
name: "default name",
tag: "__$__"
},
{
name: "some name",
tag: "some tag"
},
{
name: "some name1",
tag: "some tag1"
},
{
name: "some name1-2",
tag: "some tag1"
},
{
name: "some name2",
tag: "some tag2"
},
{
name: "some name2-2",
tag: "some tag2"
}
];
Than expand your selector to :
//filter the results based on the value of tags dropdown
let optionsToAdd = result.filter(item => item.tag === "__$__" || item.tag === tagValue);
The advantage of this is that you keep your role separated between the source of the data and the rendering.
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'm really new to AngularJS and i like it very much.
But i'm experiencing a problem trying to initialize a prealoaded dropdown with a specific value.
The dropdown is initialized with values available from JSON array, but when i try to select a default value in this dropdown, i don't see that value selected but the ng-model variable is set correctly.
I created a plunker example here http://plnkr.co/edit/7su3Etr1JNYEz324CMy7?p=preview tryng to achieve what i want, but i can't get it to work. I tried with ng-repeat and ng-select, with no luck. Another try i did (in this example) is trying to set the ng-selected property.
This is a part of my html
<body ng-controller="MySampleController">
<select name="repeatSelect" id="repeatSelect" ng-model="SelectedStatus" ng-init="SelectedStatus">
<option ng-repeat="option in StatusList[0]" value="{{option.key}}" ng-selected="{{option.key==SelectedStatus}}">{{option.name}}</option>
</select>
<select name="repeatSelect" id="repeatSelect" ng-model="SelectedOrigin">
<option ng-repeat="option in OriginList[0]" value="{{option.key}}" ng-selected="{{option.key == SelectedOrigin}}">{{option.key}} - {{option.name}}</option>
</select>
<pre>Selected Value For Status: {{SelectedStatus}}</pre>
<pre>{{StatusList[0]}}</pre>
<pre>Selected Value For Origin: {{SelectedOrigin}}</pre>
<pre>{{OriginList[0]}}</pre>
</body>
And this is code from my controller
function MySampleController($scope) {
$scope.StatusList = [];
$scope.OriginList = [];
$scope.ServiceCall = {};
$scope.EntityList = [];
$scope.SelectedStatus = -3;
$scope.SelectedOrigin = 1;
var myList = [
{
item: 'Status',
values: [{ key: -3, name: 'Aperto' },
{ key: -1, name: 'Chiuso' }]
},
{
item: 'Origin',
values: [{ key: 1, name: 'Origin1' },
{ key: 2, name: 'Origin2' },
{ key: 3, name: 'Origin3' }]
}
];
$scope.documentsData = myList;
angular.forEach($scope.documentsData, function (value) {
$scope.EntityList.push(value);
switch ($scope.EntityList[0].item) {
case 'Status':
$scope.StatusList.push($scope.EntityList[0].values);
$scope.EntityList = [];
break;
case 'Origin':
$scope.OriginList.push($scope.EntityList[0].values);
$scope.EntityList = [];
break;
}
});
}
Any help would be appreciated!
Thanks in advance.
You can at least use ng-options instead of ng-repeat + option, in which case the default value works just fine.
<select name="repeatSelect" id="repeatSelect"
ng-options="opt.key as opt.key+'-'+opt.name for opt in StatusList[0]"
ng-model="SelectedStatus"></select>`
You can also make it a bit more readable by specifying the option label as a scope function.
HTML: ng-options="opt.key as getOptionLabel(opt) for opt in StatusList[0]"
Controller:
$scope.getOptionLabel = function(option) {
return option.key + " - " + option.name;
}
Plunker: http://plnkr.co/edit/7BcAuzX5JV7lCQh772oo?p=preview
Value of a select directive used without ngOptions is always a string.
Set as following and it would work
$scope.SelectedStatus = '-3';
$scope.SelectedOrigin = '1';
Read answer here in details ng-selected does not work with ng-repeat to set default value
I am totally new to Bootstrap and angularjs world and I am stuck at this.
I have a simple select like this below
<div class="pull-left margin-left-20">
<select id="ddlPageSize" class="form-control form-ddl-adj"
ng-model="params.settings().countSelected"
ng-options="item.value as item.text for item in params.settings().countOptions"
ng-change="params.count(params.settings().countSelected)"></select>
</div>
In the controller, I have select values like this
var pageSizeList = [
{ value: 5, text: "5" },
{ value: 10, text: "10" },
{ value: 25, text: "25" },
{ value: 50, text: "50" },
{ value: 100, text: "100" }
];
5 is the option by default. Can some one tell me how to save user selection (say 10) in a cookie so that next time 10 should be the pagesize
You can use ngCookies module of AngularJS. You'll have to include angular-cookies.js in your code: https://code.angularjs.org/1.4.3/angular-cookies.min.js
Include ngCookies in your module declaration:
angular.module('testApp', ['ngCookies'])
Then you can save a cookie as:
$cookies.put('someKey', 'someVal');
You can retrieve a cookie as:
$cookies.get('someKey')
Updated:
Check this fiddle: http://jsfiddle.net/3xyf1bzo/
You can do this with ng-cookies
dropdown selection code html :
<div class="custom-param" ng-controller="themectrl">
<label id="default-lang" class="label">Default Theme:</label>
<select ng-change="themeChange(theme)" ng-model="theme" ng-options="theme.url as theme.name for theme in themes">
</select>
</div>
angularJS code :
var app = angular.module('themectrl', ['pascalprecht.translate','ngCookies'] );
app.controller('themeCtrl', function( $scope , $cookies ) {
$scope.theme = 'theme1.value';
// create the list of bootswatches
$scope.themes = [
{ name: 'Theme 1', url: 'theme1.value' },
{ name: 'Theme 2', url: 'theme2.value' }
];
// on dropdown change function
$scope.themeChange = function($selectedTheme) {
$cookies.put('ppcdfavtheme', $selectedTheme);
$scope.theme = $selectedTheme;
}
});
You can use Persistence Using local storage to save your data if you want I leave a link with working example Good luckAngularJS: Real Time Model Persistence Using Local Storage
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.