Can't remove blank select <option> created by ng-repeat in AngularJS - javascript

This is a common problem however when trying to use the solutions provided here on Stackoverflow I am having no success... I have the following in my HTML view:
<select class="date-input" ng-model="reservation.date">
<option ng-repeat="d in dates track by $index"
value="{{ d }}"
> {{ d }} </option>
</select>
In my controller I have the following...
$scope.makeDates = (function () {
dArray =[];
// we make a big array of dates ['dd-mm-yyyy','dd-mm-yyyy', 'dd-mm-yyyy'...] for 3 months and return it
return dArray;
}();
$scope.reservation = {
date : null,
time : null,
quantity : null
};
$scope.dates = $scope.makeDates;
$scope.reservation.date = $scope.dates[0];
However despite me setting $scope.reservation.date = $scope.dates[0]; the select still produces a blank option and is the default/selected value!?!?! Am I missing something? I know it is early but I can't see what I am doing wrong?

You don't need attribute value="{{ d }}" for <option>. This is a reason why you get empty item.
HTML
<div ng-app='myApp' ng-controller="ArrayController">
<select class="date-input" ng-model="reservation.date">
<option ng-repeat="d in dates track by $index">{{d}}</option>
</select>
</div>
Demo Fiddle

Related

Angular: drop-downs are not working for the ng-selected option

The selected item is not showing in the drop-down
Html
<select ng-model="selectedItemvalue">
<option value="">--Select --</option>
<option ng-repeat="sel in selectables" ng-selected="selectedItemvalue == sel" value="{{sel}}">{{sel}}</option>
</select>
Controller
$scope.selectables = ["A","B","C"]
$scope.selectedItemvalue = ["C"];
Sample Code Link 1 : https://plnkr.co/edit/talQLhVXuVZRUlMQXUmW?p=preview . - with Angular 1.0.7
Sample Code Link 2 : http://jsfiddle.net/hwr7po1m/3/ - With angular 1.6.10
Selected item is not displaying in the dropdown
Should show the selected item
Selected item value should be a string instead of array
just change
$scope.selectedItemvalue = ["C"];
to
$scope.selectedItemvalue = "C";
Working plunker
The problem is that you're setting the selectedItem initially to an array of one string (["item"] in the first example and ["C"] in the second example) instead of setting it to the value of the selected item.
It works in the Angular 1.6.10 because in that version of angular "C" == ["C"] evaluates to TRUE.
In Angular 1.0.7 "C" == ["C"] evaluates to FALSE.
So to fix your issue, you should set your selected item to be the string "C".
JS:
$scope.items = ["item1", "item2", "item3"];
$scope.selectedItem = "item1";
HTML:
<div class="field">
<select id="" class="ui fluid search dropdown" ng-model="selectedItem">
<option value=" ">Select Value</option>
<option ng-repeat="item in items" ng-selected="item == selectedItem" ng-value="item">{{item}}</option>
</select>
</div>
UPDATE: It seems like the confusion is you're asking why I am "converting" the selected item to a string. I'm not converting anything actually. The original list is an ARRAY of STRINGS, so each individual item in the array is a string. Therefore by having the selected item be of type string, I'm only calling the item in the list what it actually is.

AngularJS variable not updating in view

A question that has been asked (and answered) a thousand times, yet I can't figure this out.
I'm trying to update the option labels of a select box based on the value of another.
Select code for the source of the new label:
<select id="year" name="year" ng-model="Data.year" ng-change="updateAge(Data.year)">
Option value code for the target of the new label
<option value="low">{{ Age.low }}</option>
Controller code to update the scope variable. The second console log displays the updated age, but that isn't shown in the view. I've tried $scope.$apply() but Angular errors because $apply is already in progress.
$scope.updateAge = function( year ) {
if ( year == '2016' ) {
console.log($scope.Age.low);
$scope.Age.low = 'NEW AGE';
console.log($scope.Age.low);
}
}
Some observations :
As you set the option value as "low". Hence, on updateAge function call this block if ( year == '2016' ) { ... } will not execute because year value will always be low.
Make option value also dynamic.
try <option value="{{ Age.low }}">{{ Age.low }}</option>
instead of <option value="low">{{ Age.low }}</option>
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.Age = {"low": '2016'};
$scope.updateAge = function(year) {
if (year == '2016') {
console.log($scope.Age.low);
$scope.Age.low = 'NEW AGE';
console.log($scope.Age.low);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select id="year" name="year" ng-model="Data.year" ng-change="updateAge(Data.year)">
<option value="{{ Age.low }}">{{ Age.low }}</option>
</select>
</div>

Select2 multiple select default selections not working

This is my html code
<select name="age_group[]" class="form-control age_group" multiple="multiple">
#foreach($age_groups as $group)
<option value="{{ $group->id }}">{{ $group->age_group_name }}</option>
#endforeach
</select>
And this is the JS
var selected = [1, 2, 3];
// initialize select2 for age group
$(".age_group").select2();
$(".age_group").select2('val', selected);
What I want to do is set default values as selected as suggested by this post. But in my code above I am only getting the first element of the array as selected.
Can anyone tell me what's wrong with my code?
Jsfiddle demo
Try like this it will work:
$(".age_group").val(selectedvalue).trigger("change");
sample fiddle : http://jsfiddle.net/fyhsz9ra/891/
You need to specify the value you need to select.
$('select').select2().select2('val', $('.select2 option:eq(1)').val());
OR
Split the values before Passing to the Select2();
var values = //split the string ;
$(".age_group").select2('val',values);
Hope this Helps you.

Angular select, ng-init with dynamic value

I'm trying to get a select box working in Angular. The problem I'm experiencing is to do with ng-init and setting it's default value from an object which is created during runtime. Heres my code:
<select
ng-model="settings.editing.panel.data.production_company"
ng-change="settings.editing.panel.data.production_company = selectValue"
ng-init="selectValue = settings.editing.panel.data.production_company"
>
<option
ng-repeat="(key, value) in lists.production_companies"
value="{{key}}"
ng-selected="{{selectValue}}"
>
{{value}}
</option>
</select>
"lists.production_companies" is a simple key-value array of names, populated during initial page render, updated by ajax.
The object "settings.editing.panel.data" starts its life as NULL, but later is loaded with a correctly formatted object which contains the property "production_company".
I have found setting ng-init to something like "ng-init="selectValue = 3" works fine. Setting a $scope.test = 3, then setting "ng-init="selectValue = test" works fine too.
However, my dynamic value does not work. How can I use my dynamically created object to set the value of this select box during runtime with the set-up I have?
<select
ng-model="settings.editing.panel.data.production_company"
ng-options = "option as option.keyName for option in list.production_companies"
> <!--set keyName equal to your object's key-->
</select>
Then in your controller
$scope.settings.editing.panel.data.production_company = list.production_companies[0] // Or which value you want to assign
You question confused me somehow. The following snippet is a working one, is that what you want?
'use strict';
angular.module('DemoApp', []);
angular.module('DemoApp').controller('DemoCtrl', ['$scope', function($scope){
$scope.lists={
production_companies: { "0": "prod 1", "1":"prod_2" },
};
$scope.settings={
editing: {
panel: {
data: null
}
}
};
$scope.setData=function(data){
$scope.settings.editing.panel.data={
production_company: data
};
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="DemoApp" ng-controller="DemoCtrl">
<select ng-model = "settings.editing.panel.data.production_company">
<option ng-repeat = "(key, value) in lists.production_companies" value = "{{key}}">{{value}}</option>
</select>
<div>You select: {{settings.editing.panel.data.production_company}}</div>
<button ng-click="setData('0')">Set Data to Prod1</button>
<button ng-click="setData('1')">Set Data to Prod2</button>
</div>
In my circumstances I was able to change my backends data format to set an object like:
{"id": 1, "name":"prod comp 1"}
and then change my select model accordingly. In hindsight I needed this for the ID anyway.
<select
ng-model="settings.editing.panel.data.production_company"
>
<option
ng-repeat="option in settings.lists.production_companies"
value="{{option.id}}"
ng-selected="{{option.id}} == settings.editing.panel.data.production_company"
>
{{option.name}}
</option>
</select>

Get values selected from SelectBox Angularjs

I'm new to Angularjs and I have selectBox with two variables (startDate and endDate):
<div>
<select class="form-control" ng-model="date.time">
<option ng-repeat="time in dateList" value="{{time.startDate}},{{time.endDate}}" >
{{time.startDate| date:'medium'}} - {{time.endDate | date:'medium'}}</option>
</select>
</div>
After the user select a period I want to get the startDate and endDate separately.
Did you try looking at what your value holds when you're done selecting? You'll get the string you put inside the option's value.
var dates = $scope.date.time.split(','),
startDate = dates[0],
endDate = dates[1];
With the ng-options syntax you can set to your date.time the whole object:
<select class="form-control" ng-model="date.time" ng-options="time as ((time.startDate | date:'medium') + ' - ' + (time.endDate | date:'medium')) for time in dateList"></select>
What ever you have bound in your ng-model will hold the selected value.
In your case the ng-model is holding date.time, which may not be what you are looking for.
Additionally you should set the value to be the data that you wish to extract from the option list.
Please see this (poorly and quickly constructed) jsFiddle
html
<div ng-controller="MyCtrl">
<select class="form-control" ng-model="selected">
<option ng-repeat="time in dateList" value="{{time}}" >
{{time.prop}}</option>
</select>
{{selected}}
</div>
js
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.selected = 'plz select a thing';
$scope.dateList = [{prop:'prop1'}, {prop:'prop2'}];
}

Categories