How to dynamically set value for Angularjs select?

61 views Asked by At

In Angularjs, I try to set option dynamically from program. But, I am not able to set.

Please support.

Verify comment's reference link for more details.

Thanks in Advance!

<div ng-app="myApp">
    <div ng-controller="AppCtrl">
        "AngularJS select example"
        <br />
         <br />
        <select ng-model="mail_notification" ng-change="plotRulegraph()">
           <option ng-selected="{{ option.key == mail_notification }}"
                   ng-repeat="option in mail_notifications"
                   value="{{option.key}}">
             {{option.value}}
           </option>
        </select>
        <br />                
    </div>
</div>
app.controller('AppCtrl', function($scope){
    $scope.mail_notifications = [
        {
            "key": 0,
            "value": "For any event on all my projects"
        },
        {
            "key":1,
            "value": "For any event on the selected projects only..."
        },
        {
            "key": 2,
            "value": "Only for things I watch or I'm involved in"
        },
        {
            "key": 3,
            "value": "Only for things I am assigned to"
        }
    ];
    $scope.mail_notification = 3;

     $scope.plotRulegraph = function() {
            $scope.mail_notification=2;
     }
});
1

There are 1 answers

2
georgeawg On

Don't use ng-selected with ng-model.

When the values are a type other that strings, use the ng-value directive:

<div ng-app="myApp">
    <div ng-controller="AppCtrl">
        "AngularJS select example"
        <br />
         <br />
        <select ng-model="mail_notification" ng-change="plotRulegraph()">
           <option ̶n̶g̶-̶s̶e̶l̶e̶c̶t̶e̶d̶=̶"̶{̶{̶ ̶o̶p̶t̶i̶o̶n̶.̶k̶e̶y̶ ̶=̶=̶ ̶m̶a̶i̶l̶_̶n̶o̶t̶i̶f̶i̶c̶a̶t̶i̶o̶n̶ ̶}̶}̶"
                   ng-repeat="option in mail_notifications"
                   ̶v̶a̶l̶u̶e̶=̶"̶{̶{̶o̶p̶t̶i̶o̶n̶.̶k̶e̶y̶}̶}̶"̶
                   ng-value="option.key">
             {{option.value}}
           </option>
        </select>
        <br />                
    </div>
</div>

With interpolation with double curley braces {{ }}, the values are converted to strings. The <select> directive uses strict equality when comparing values. Numeric keys are not equal to string keys. The ng-value directive retains the proper type.

From the Docs:

Note: ngSelected does not interact with the <select> and ngModel directives, it only sets the selected attribute on the element. If you are using ngModel on the <select>, you should not use ngSelected on the options, as ngModel will set the <select> value and selected options.

AngularJS ng-selected Directive API Reference

For more information, see


Update

The example requires AngularJS V1.5 or greater.

The DEMO on PLNKR.