Reset select to default value with AngularJS - angularjs

I have a following question for AngularJS. I have a
select with options created with ngOptions. I want to
set selected option back to default option. I tried to
delete model variable e.g:
if(angular.isDefined($scope.first)){
delete $scope.first;
}
But this not working. Here is my html.
<div ng-app="app">
<div ng-controller="testCtrl">
<select data-ng-model="first" data-ng-options="item.name for item in selectContent" required="required">
<option value="" style="display: none;">-- select --</option>
</select>
{{first.value}}
<hr/>
<input type="button" value="reset dropdown" data-ng-click="resetDropDown()"/>
</div>
</div>
And here is my JavaScript code:
angular.module('app', []).controller('testCtrl', function ($scope) {
$scope.selectContent = [
{
name: "first",
value: "1"
},
{
name: "second",
value: "2"
}
];
$scope.resetDropDown = function() {
if(angular.isDefined($scope.first)){
delete $scope.first;
}
}
});
Here is working jsfiddle:
http://jsfiddle.net/zono/rzJ2w/
How I can solve this problem?
Best regards.

Your reset-button is placed outside of the div containing your controller. This means that your reset-function does not exist in the context where you try to use it.
Change to:
<div ng-app="app">
<div ng-controller="testCtrl">
<select data-ng-model="first" data-ng-options="item.name for item in selectContent" required="required">
<option value="" style="display: none;">-- select --</option>
</select>
{{first.value}}
<hr/>
<input type="button" value="reset dropdown" data-ng-click="resetDropDown()"/>
</div>
</div>
It's always a good idea to use a debugger to make sure the code you're trying to fix is actually being executed.

$scope.resetDropDown = function() {
$scope.first = "";
}

Solution above works for Windows and Android, but did not work for iOS browsers. Probably events are happening in different order there.
So for my code I:
created ID for select element, so I could easily find it by
iQuery;
created delayed invocation of to statements to ensure the
reset is happenning at the very end;
and just in case was
resetting in two ways (but just first way was actually enough in iOS
too);
function resetDropDown () {
$timeout(function(){
$scope.first = '';
// jQuery way
$('select#idOfSelectElement option:first' ).prop( 'selected', true );
}, 200);
}

Related

how to use ng-switch with ng-repeate in select

I am trying to show and hide one of two select options based on an expression
but it doesn't work well. How can I make it work? Thanks in advance.
<div class="col-md-3">
<div class="form-group has-error " ng-switch on="class">
<label class="title_lable">{{class}}</label>
<select class="form-control input-sm" ng-model="Tclass">
<option ng-switch-when="7" ng-repeat="sd in ScientificDegree" value="{{sd.sub_cod}}">{{sd.Degree}}</option>
<option ng-switch-when="8" ng-repeat="sp in Specialty" value="{{sp.Spec_Key}}">{{sp.Spec}}</option>
</select>
</div>
</div>
Would be better if you include the controller's content in your question, but I tried to complete an example based on some assumptions. Your ng-switch looks good, so I think something is wrong in the controller. This is what I put in the controller to get it working:
app.controller('MainCtrl', function($scope) {
$scope.ScientificDegree = [{sub_cod:1,Degree:'Degree 1'}];
$scope.Specialty = [{Spec_Key: 2, Spec: 'Specialty 2'}];
$scope.TClass = '';
$scope.class = 8;
});
Here's a plunker to see it working https://plnkr.co/edit/TjE2MvrHLfdI1umajtBx?p=preview

Based on dropdown value show div inside ng-repeat

The below thing is taking too much time than expected. Been through top stack solutions and somehow got the below thing--
WHAT IS THE SCENERIO
I have an ng-repeat div with dropdown.
The drop down contains values and based on selection of those values a div will be shown. What I managed is div is shown. But when I choose another item the previous item div gets hidden.
Below are the screen shot and my code
As it can be seen that when I select the first item it shows the textbox div. But when I select the next item the first gets hidden. There are essentially two values -- ALL, Fixed. When All selected nothing will be shown and when Fixed is selected the div for that particular item will be shown.
HTML code
<div class="tst text-success" ng-repeat="(parentIndex, catList) in categoryArray">
<div class="col-md-3">
{{catList.categoryName}}
</div>
<div class="col-md-4">
<select class="form-control m-b" ng-model="catObj.cats" ng-change="changeOption(catObj,parentIndex)">
<option value="All">All</option>
<option value="fixed">Fixed No. Of Records</option>
<option value="perfixed">% od Fixed</option>
</select>
</div>
<div class="col-md-3 noPad" ng-if="isShowing==parentIndex">
<input type="text" class="form-control form-control-small" placeholder="Set Number" />
</div>
</div>
CONTROLLER
$scope.changeOption = function(obVal,index) {
console.log(obVal);
console.log(index);
if(obVal.cats == "All") {
//$scope.tbx = 0;
}
else {
$scope.isShowing = index;
}
}
Help would be appreciated
Thanks
You're using a single boolean $scope variable, isShowing, to control the visibility of several divs. That can't possibly work.
You should
have an array of objects, each having a selectedOption field.
use ng-model in your select box to set the selectedOption of the object you're editing.
use the value of the object's selectedOption to know if the additional input should be visible for that object.
Example:
<div ng-repeat="obj in objects">
{{ obj.name }}
<select name="op" ng-model="obj.selectedOption" ng-options="option.value as option.value for option in options"></select>
<input ng-if="obj.selectedOption !== 'All'" />
</div>
app.controller('MainCtrl', function($scope) {
$scope.options = [
{value: 'All'},
{value: 'Fixed'}
];
$scope.objects = [
{name: 'Twitter', selectedOption: 'All'},
{name: 'News', selectedOption: 'Fixed'}
]
});

How to remove item from an array

I have a dropdown where items are populated from $scope.role. Now I need to remove the values from $scope.role once the value is added or selected in dropdown. I did splice(index,1) which actually delete the first element only. Need assistance.
$scope.role = ['Actor', 'Director/ Asst. director', 'Lyricist',
'Music director/ Asst. director', 'Singer', 'Standup Comedian', 'Model',
'Cinematographer', 'Photographer', 'Script Writer', 'Choreographer',
'Editor/ Promo editor', 'Costume designer', 'Art director', 'Stunt artist',
'Voice-over artist', 'Graphic Designer', 'Screenplay', 'Dialogue',
'Back ground music'];
Html:
<div class="row newRow">
<div class="form-group fields col-sm-2 col-xs-4">
<label>ROLE *</label>
<select name="role" class="form-control1 drop2" required ng-model="model.role" placeholder="select">
<option value='' disabled selected>Select</option>
<option ng-repeat="item in role track by $index" value="{{item}}">{{item}}</option>
</select>
</div>
<div class="form-group col-sm-2 col-xs-4">
<button ng-click="AddRole()">Click to Add Role</button>
</div>
</div>
JS:
$scope.multiRoles = [];
$scope.role == $scope.dummy;
$scope.rolesAdded = false;
$scope.AddRole = function(index) {
debugger;
if ($scope.model.role !== undefined) {
$scope.multiRoles.push($scope.model.role);
$scope.role.splice(index, 1);
console.log($scope.role);
}
};
You can do it in two ways 1) As suggested by #nikjohn by sending your $index of dropdown in ng-click = "AddRole($index)" and then splice or else
2) You can find the index of the selected option by using the ng-model binded to the dropdown.
$scope.AddRole = function(){
debugger;
if($scope.model.role !== undefined ){
$scope.multiRoles.push($scope.model.role);
var index = $scope.role.indexOf($scope.model.role); //just find the right index which is the selected option in dropdown.
$scope.role.splice(index,1);
console.log($scope.role);
}
};
In your HTML, pass $index to the AddRole. Otherwise, the function does not know what $index is, and also include the button within the ng-repeat:
<select name="role"
class="form-control1 drop2" required
ng-model="model.role" placeholder="select">
<option value='' disabled selected>Select</option>
<option ng-repeat="item in role track by $index" value="{{item}}"> {{item}}
<button ng-click = "AddRole($index)">Click to Add Role</button>
</option>
</select>
In your Controller, there's an extra = that I've highlighted in my comment:
$scope.multiRoles = [];
$scope.role == $scope.dummy; // Why a `==` here? This should be a `=`
$scope.rolesAdded = false;
$scope.AddRole = function(index){
debugger;
if($scope.model.role.length){ // Cleaner method to verify that the array is non-empty
$scope.multiRoles.push($scope.model.role);
$scope.role.splice(index,1);
console.log($scope.role);
}
};
May I also suggest that you use Angular's select implementation with ng-options because:
Choosing between ngRepeat and ngOptions
In many cases, ngRepeat can be used on elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits:
more flexibility in how the <select>'s model is assigned via the select as part of the comprehension expression
reduced memory consumption by not creating a new scope for each repeated instance
increased render speed by creating the options in a documentFragment instead of individually
Specifically, select with repeated options slows down significantly starting at 2000 options in Chrome and Internet Explorer / Edge.

Why does Angular add an empty <option> if the value exist in the provided options?

I have read on many occasions that Angular tends to add an empty option at the beginning of the select element if the value of the model does not exist among the offered options.
However, I have a model whose value is set to 0 from the start, and 0 is provided as one of the options in the select element as well, yet there is still one empty option above my own options. It disappears after the actual option whose value is 0 gets selected.
Why is this and how do I get rid of it?
A very simple example of the problem I am experiencing is displayed here: http://jsfiddle.net/yuvnz7wr/
The javascript code:
var app = angular.module('Module', []);
app.controller('Test', function ($scope) {
$scope.model = 0;
$scope.options = [{
id: 0,
name: 'Zero'
}, {
id: 1,
name: 'One'
}];
});
The HTML code:
<div ng-app="Module">
<div ng-controller="Test as test">{{model}}
<select ng-model="model">
<option ng-repeat="option in options" ng-value="option.id">{{option.name}}</option>
</select>
</div>
</div>
You better use ng-options and ng-init directives for <select> with angular:
<div ng-app="Module">
<div ng-controller="Test as test">{{model}}
<select ng-model="model" ng-init="model = options[0].id" ng-options="option.id as option.name for option in options"></select>
</div>
</div>

Angularjs ng-selected populate

I am trying to populate the currently selected item in angular js.
The currently selected item is that with the id in event.email.chases[0].id
and I am trying to match it to a select box populated from case.activeChases
This does what I want so far, which updates whenever the select box changes.
<select
class="form-control"
name="chase"
id="chase"
ng-model="customer.chase"
ng-change="addEmailToChase(customer.chase.id, event.email.id)"
ng-options="cor as cor.emails[0].subject for cor in case.activeChases">
<option value="">None</option>
</select>
I need to find the chase in activeChases with activeChases[x].id = event.email.chases[0].id, so the correct value is selected upon the page load.
Could I possibly do this all within a ng-selected attribute?
Something wrong with your model and your ng-options, the object should be the same if you want an "auto-selected"
without a jsfiddle it's hard to reproduce your situation but I tryed something like that
var app = angular.module('App', []);
app.controller('Ctrl', function($scope) {
$scope.case = {
activeChases: [{
emails: [{
subject: 'toto'
}]
}, {
emails: [{
subject: 'tata'
}]
}]
};
// set "default value"
$scope.customer = {
chase: $scope.case.activeChases[1]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="App" ng-controller="Ctrl">
<select class="form-control" name="chase" id="chase" ng-model="customer.chase" ng-change="addEmailToChase(customer.chase.id, event.email.id)" ng-options="cor as cor.emails[0].subject for cor in case.activeChases">
<option value="">None</option>
</select>
</section>
So this was my answer:
<select
class="form-control"
name="chase"
id="chase"
ng-model="event.email.chases[0].id"
ng-change="addEmailToChase(event.email.chases[0].id, event.email.id)"
ng-options="cor.id[0] as cor.emails[0].subject for cor in case.activeChases">
</select>
I wanted the default value to be event.email.chases[0].id in the select, so I just set ng-model to that, and changed the first option to cor.id[0] to use id in index.
I chose a random name for ng-model which was customer.chase which made no sense. event represents an ajax loaded form element so its safe for me to do this in my scope.
Also worth noting that the id in cor.id[0] is actually in a size one array due to incorrect design in the app.

Resources