7

I can't get a placeholder idea with select. With the below the first entry is still blank.

<select class="form-control" ng-model="refData" required>
     <option ng-repeat="d in refData">
          {{d.value}}
     </option>
     <option value="" disabled hidden selected>View current values</option>
</select>
lin
  • 17,956
  • 4
  • 59
  • 83
user441521
  • 6,942
  • 23
  • 88
  • 160
  • It is interesting why ng-repeat doesn't work but ng-options does. – user441521 Mar 13 '17 at 15:07
  • 1
    I dont know why you accept an answer which does not match with your requirements? There is no placeholder logic in that answer, it may will confuse other users who reffers this as an possible answer for "Placeholder for select with AngularJS". – lin Mar 13 '17 at 15:08
  • You made a good case. Changed. – user441521 Mar 13 '17 at 15:12
  • Now its much more helpful for all users. The right answer now reffers to the question requirements. Cheers m8 – lin Mar 13 '17 at 15:14

3 Answers3

28

You can use transclusion to add an extra option that is disabled and selected. See How do I make a placeholder for a 'select' box? for more background on that general solution. Here is the ngSelect documentation for reference, as well.

View

<div ng-controller="MyCtrl">
    <select name="mySelect" 
            id="mySelect"
            ng-options="option.name for option in refData track by option.id"
            ng-model="selectedOption">
         <option value="" disabled selected>View current values</option>
     </select>
</div>

AngularJS application

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    $scope.refData = [
      {id: '1', name: 'Option A'},
      {id: '2', name: 'Option B'},
      {id: '3', name: 'Option C'}
    ];

    $scope.selectedOption =  "";
});

JsFiddle Demo

AlexMA
  • 9,842
  • 7
  • 42
  • 64
lin
  • 17,956
  • 4
  • 59
  • 83
2
<select ng-model="testData" ng-options="test.name for test in testData">
        <option value="" selected>View current values</option>
</select>

Given test data is:

$scope.testData = [{"name" : "John"}, {"name" : "Micheal"}, {"name" : "Sarah"}];
Nehal Soni
  • 186
  • 1
  • 9
1

I suggest using ng-options

<select ng-options="d as d.value for d in refData" ng-model="refDataSelected"></select>

On your controller you can declare

$scope.refDataSelected = refData[0]

to use first element as default option

If you want to create a dummy text you can add a new object to refData with custom text and give it an unreal id like -1. But when you submit you should check whether its id is -1 or not.

necilAlbayrak
  • 824
  • 6
  • 9
  • I don't want to have the first one as the default. I want a message that says whatever I want it to say but it's not an option to select. – user441521 Mar 13 '17 at 14:57
  • Interesting that using ng-options worked but ng-repeat doesn't. Oh well, thanks. – user441521 Mar 13 '17 at 14:59