javascriptarraysangularjsng-options

Pre-set option in select box with customized text in Angular JS


I want to pre set my select box by using whole object available in my array. the text will be customized by using object fields as shown in below image

Pre select object

this is what I have tried so far

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="employee" ng-options="item as (item.name+' - '+item.post) for item in employees">
<option value="">select</option>
</select>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.employees = [{name:"Mehtab",post:"SE"}, {name:"Punit", post:"PM"}, {name:"Ashutosh", post:"SSE"}];
    $scope.employee = {name:"Punit", post:"PM"};
});
</script>

</body>
</html>


Solution

  • Is this you want:

    html:

    <select ng-model="employee.name" ng-options='item.name as (item.name + " - " + item.post) for item in employees'>
    <option value="">select</option>
    

    JS:

    $scope.employees = [
          {name:"Mehtab",post:"SE"}, 
          {name:"Punit", post:"PM"}, 
          {name:"Ashutosh", post:"SSE"}
        ];
    $scope.employee = {"name":"Punit","post":"PM"};
    

    Working fiddle: https://jsfiddle.net/rum25Lxz/