Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset select to default value with AngularJS

Tags:

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.

like image 606
Georgi Naumov Avatar asked Jul 28 '14 08:07

Georgi Naumov


People also ask

How to set default value in select option using jQuery?

if your wanting to use jQuery for this, try the following code. $('select option[value="1"]'). attr("selected",true);

How do I set default value in Ng?

Use ng-init to set default value for ng-options .

How to reset select DropDown value in jQuery?

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).


1 Answers

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.

like image 128
ivarni Avatar answered Sep 20 '22 13:09

ivarni