SHIVANG SANGHI
SHIVANG SANGHI

Reputation: 465

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.

Upvotes: 13

Views: 19607

Answers (2)

Madan Sapkota
Madan Sapkota

Reputation: 26091

First create data (can be local or from server) in Controller. And initialize the default value, which force the default item selected in HTML form.

// supported languages
$scope.languages = ['ENGLISH', 'SPANISH', 'RUSSIAN', 'HINDI', 'NEPALI'];
// init default language
$scope.language = 'ENGLISH';

Now in your HTML form

<select class="form-control" ng-model="language">
    <option ng-repeat="language in languages">{{language}}</option>
</select>


The screenshot is here (note bootstrap CSS is used and not included here).

enter image description here


You can do a test in controller, whether the change is working

$scope.$watch('language', function (newVal, oldVal) {
    console.log(oldVal + " -> " + newVal);
});

ENGLISH -> RUSSIAN

RUSSIAN -> SPANISH

SPANISH -> RUSSIAN

Hope this is helpful. Thanks!

Upvotes: 3

basarat
basarat

Reputation: 275947

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/

Upvotes: 21

Related Questions