Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ngModel directive in select

I am working on an angularjs project and i have a problem with the ngModel not binding within the select.But the same concept is working in another select tag and in the same html page. Below is the code.

  <select ng-model="selectedFont" 
          ng-options="font.title for font in fonts" 
          ng-change="onFontChange()">
  </select>

onFontChange() function is placed in the controller.

Anyone help is highly appreciable...Thanks in advance.

like image 553
SHIVANG SANGHI Avatar asked Apr 29 '13 06:04

SHIVANG SANGHI


People also ask

Can we use ngModel for select?

The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.

What is [( ngModel )]?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

How do I set default selected value in ng-options?

Use ng-init to set default value for ng-options . Save this answer.

How does ngModel work in AngularJS?

The ngModel directive binds an input , select , textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.


1 Answers

Based on Tony the Pony's fiddle :

<div ng-app ng-controller="MyCtrl">
    <select ng-model="opt"
            ng-options="font.title for font in fonts"
            ng-change="change(opt)">
    </select>

    <p>{{opt}}</p>
</div>

With a controller:

function MyCtrl($scope) {
    $scope.fonts = [
        {title: "Arial" , text: 'Url for Arial' },
        {title: "Helvetica" , text: 'Url for Helvetica' }
    ];
    $scope.change= function(option){
        alert(option.title);
    }
}

http://jsfiddle.net/basarat/3y5Pw/43/

like image 115
basarat Avatar answered Sep 19 '22 18:09

basarat