Search code examples
htmlangularjsangularjs-ng-options

Getting ng-option text inside html


My Code:

HTML:

<select ng-model="selectedItem" ng-options="item.result as item.name for item in items"></select>

JS:

$scope.items = [{'name': 'Yes', 'result': true },{ 'name': 'No', 'result': false }];

I want to display Yes and No in the select box whereas I have to send true and false to the server when Yes or No is selected respectively.

I have another div where I have to display the option text (ie Yes or No (selected one) ). I used {{selectedItem.label}} but it is not working. Please help.


Solution

  • Used Sajeetharan's answer and updated it to meet your requirement. Following is the code:

    <!DOCTYPE html>
    <html ng-app="todoApp">
    
    <head>
    <title>To Do List</title>
    <link href="skeleton.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="MainViewController.js"></script>
    </head>
    
    
    <body ng-controller="dobController">
        <select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.result as selection.name for selection in items"></select>
        <div>
            <h1> Selected one is : {{currentSelected? "Yes": (currentSelected == null)? "":"No"}} </h1>
        </div>
        <script>
            var app = angular.module('todoApp', []);
    
            app.controller("dobController", ["$scope",
            function($scope) {
    
                $scope.items = [{'name': 'Yes', 'result': true },{ 'name': 'No', 'result': false }];
            }
            ]);
    
        </script>
    </body>
    
    </html>