Default value in Select field - javascript

I am confused about why I am getting this specific malfunction, I am unable to get a default value for my select dropdown list. My goal is to have "Choose Board" as the default but despite many trials, I have been unable to get this as the default value.
I have attempted a variety of solutions: AngularJS - Set default value on select inside a ng-repeat & How to have a default option in Angular.js select box
Without any luck.
My HTML Tags:
<select name="boardInput" class="form-control"
ng-required="true"
ng-init="form.boardInput = boards[0]"
ng-model="form.boardInput"
ng-options="board.name for board in boards">
</select>
My JS controller code
//TRELLO CONTROLLER
$scope.baseBoards =[{
id: false,
name: "Choose Board"
}];
$scope.getBoards = function() {
trello.getBoards('me', function(error, boards){
if(error){
log("Could Not Get Boards: ", error);
} else {
log("found " + boards.length + " boards");
$scope.boards = $scope.baseBoards.concat(boards);
}
});
};
The result is a field being added and set as the default, in the above code the null field disappears after any of the others are selected.
any help is much appreciated.

Try
<select name="boardInput" class="form-control"
ng-required="true"
ng-model="form.boardInput"
ng-options="board.name for board in boards">
</select>
and in your Controller
$scope.form.boardInput = "Choose Board"
If it works then you can replace the text with your desired variable such as $scope.baseBoards[0].name.

Please check this updated answer. For now your trello.getBoards I have commented, once you add it in your code, uncomment it and comment var boards this variable.
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope) {
$scope.boards = [];
$scope.baseBoards = [{
id: false,
name: "Choose Board"
}];
$scope.getBoards = function() {
/* trello.getBoards('me', function(error, boards) {
if (error) {
log("Could Not Get Boards: ", error);
} else {
log("found " + boards.length + " boards");
$scope.boards = $scope.baseBoards.concat(boards);
}
}); */
//You will get boards data from your trello.getBoards method but I dont have access it so declaring local variable.
var boards = [{
name: 'one'
}, {
name: 'two'
}, {
name: 'three'
}]
$scope.boards = $scope.baseBoards.concat(boards);
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app='app' ng-controller='myController' ng-init="getBoards()">
<select name="boardInput" class="form-control" ng-required="true" ng-init="form.boardInput = boards[0]" ng-model="form.boardInput" ng-options="board.name for board in boards">
</select>
</div>

Related

Ng-options in angularjs to show the selected value from the json

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.

angularjs select depending on number of options in model

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

Cannot select default value in dropdown using ng-model and ng-repeat or ng-select in AngularJS

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

saving dropdown selection in cookie

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

Angular $http POST unable to bind array

So I'm trying to set up a post function using Angular. I've got a HTML form which has two text boxes (for user input) and a drop down menu for selecting a number of choices (so the user fills out the form and submits data to server).
Binding the two text boxes is fine but I don't know how to bind the two options in my array as choices in the drop down menu?
(Heres a fiddle:http://jsfiddle.net/gtv7s8h3/2/ )
Form:
<form>
<input type="text" id="name" ng-model="myForm.Title" ng-minlength="5" ng-maxlength="20"> title <br/>
<input type="text" id="name" ng-model="myForm.Content" ng-minlength="5" ng-maxlength="20"> content <br />
<select ng-model="CategoryId" ng-options="item.name for item in CategoryId"></select>
<button ng-click="myForm.submitTheForm()">Submit Form</button>
</form>
Angular POST:
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myForm = {};
$scope.myForm.Title = "";
$scope.myForm.Content = "";
$scope.CategoryId = {
data: [{
id: '316556404cac4a6bb47dd4c7ca2dac4a',
name: 'name1'
}, {
id: '306e3d9a6265480d94d0d50e144435f9',
name: 'name2'
}]
};
$scope.myForm.submitTheForm = function(item, event) {
var dataObject = {
Title : $scope.myForm.Title,
Content : $scope.myForm.Content,
CategoryId : $scope.CategoryId
};
var responsePromise = $http.post("/url", dataObject, {});
responsePromise.success(function(dataFromServer, status, headers, config) {
console.log(dataFromServer.title);
});
responsePromise.error(function(data, status, headers, config) {
alert("Submitting form failed!");
});
}
});
You're trying to bind the categoryID to you array and your ngOptions expression does not loop through your array. You need to bind the categoryId value to a different model.
Add a model for your categoryID:
$scope.myForm.categoryId = null;
and change your select markup:
<select ng-model="myForm.categoryId" ng-options="item.id as item.name for item in CategoryId.data"></select>

Categories

Resources