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.
if your wanting to use jQuery for this, try the following code. $('select option[value="1"]'). attr("selected",true);
Use ng-init to set default value for ng-options .
The following HTML Markup consists of an HTML DropDownList (DropDown) control and a Button. When the Button is clicked, the jQuery click event handler is executed. Inside this event handler, the SelectedIndex property of the DropDownList is set to 0 (First Item).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With