Search code examples
javascriptangularjsangular-ngmodelangularjs-ng-optionsangularjs-ng-model

Angular JS - get selected text as ng model (without ng-options)


In my code behind, I fill up a DropDownList as follows (using VB)

ddlCountries.DataSource = dt ' dt is DataTable with columns "CountryCode" and "CountryName"
ddlCountries.DataTextField = "CountryName"
ddlCountries.DataValueField = "CountryCode"
ddlCountries.DataBind()
ddlCountries.Attributes.Add("ng-model", "CountryName")

Then client side, I have a select tag, which is filled with options from server side as below:

<select ng-model="CountryName">
    <option value="IN">India</option>
    <option value="US">United States</option>
    <option value="ML">Malaysia</option>
    <!-- and other 200+ records -->
</select>

I can't use ng-options here! Now, whenever I change the value from select, I get CountryName as IN, US, ML etc.. Moreover, I can't edit values of options because they're used in server side code.

Here I want CountryName as India, United States or Malaysia instead! What can I do?


Solution

  • What data is the server sending you?

    Is it some array of objects like this?

    var countries = [ 
        { name: 'India', code: 'IN'},
        { name: 'United States', code: 'US'},
        { name: 'Malaysia', code: 'ML'}
    ];
    

    If yes, then you can easily use ng-options (even though you dont have to, its just better).

    <select ng-model="CountryName"
        ng-options="c.code as c.name for c in countries">
    </select>
    

    Or in the case that you actually are working with server side generated html page and no javascript objects, then its a little bit tricker: (Supposing you can use JQuery):

    view:

    <select id="countryNameSelect" ng-change="setCountryName()">
        <option value="IN">India</option>
        <option value="US">United States</option>
        <option value="ML">Malaysia</option>
        <!-- and other 200+ records -->
    </select>
    

    controller:

    $scope.countryName = '';
    $scope.setCountryName = function() {
      $scope.countryName = $("#countryNameSelect option:selected").html();
    };