angular newpiee
angular newpiee

Reputation: 41

Select drop-down selected value

I have a drop-down with some country code and its fullname in the option dropdown box. (Like Below)

    <script>
            var app = angular.module('myApp', []);
            app.controller('myCtrl', function($scope) {
            $scope.names = ["US-United state of America", "IN-India", "UK-United Kingdom"];
            });
    </script>

and my html Part is

    <select ng-model="selectedName" ng-options="x for x in names"></select>

Ok, so what I want to do is, when I select any dropdown value in the dropdown, It should be entered only "US" without its fullname.

And when I saved this data into database, I am saving "US" only from webservice call, but In UI part I need to manage these things and when I edit this record only "US" should be selected in Dropdown not "US-United state of America".

I know this is weird requirement, but we need to do this :(

Upvotes: 0

Views: 101

Answers (2)

Jeffrey Roosendaal
Jeffrey Roosendaal

Reputation: 7147

Use a filter


Template:

<select 
    ng-model="selectedName"
    ng-change="stripCountryName(x)"
    ng-options="x | stripCountryName for x in names">
</select>

Filter:

app.filter('stripCountryName', function() {
    return function(name) {
        return name.split('-')[0];
    };
});

You can also use this filter to modify the outcome after selecting an option by injecting it into your controller:

app.controller('myCtrl', function($scope, stripCountryNameFilter) {
    $scope.stripCountryName = (option) => {
        $scope.selectedName = stripCountryNameFilter(option);
    }
})

This way, your original $scope.names will always stay intact.

Upvotes: 0

Vivz
Vivz

Reputation: 6620

You can split the value in the dropdown to remove the part after hyphen - . Your names array will stay the same and you don't have to write any javascript.

var app = angular.module('myApp', [])
app.controller('myCtrl', [
    '$scope',
    function($scope) {
        $scope.names = ["US-United state of America", "IN-India", "UK-United Kingdom"];
    }
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
    <div ng-controller="myCtrl">
        <select ng-model="selectedName1" ng-options="x.split('-')[0] as x.split('-')[0] for x in names"></select> {{selectedName1}}
        <select ng-model="selectedName2" ng-options="x as x.split('-')[0] for x in names"></select> {{selectedName2}}
    </div>
</div>

Upvotes: 1

Related Questions