1

Maybe this can has duplicated or maybe there's a way to solve this,

but I couldn't find any way to solve this.

So please don't be angry with my silly question and give me some information or way to solve this.

Please see this fiddle.

Set default value of select box

What I want is, when I get array from http call,

how to set default value of select box with the value which is not in array.

I've used ng-init but it didn't work.

I know there are other ways to solve this like using <options> tag and put first value of option or

using selected but I want to use ng-options.

No matter what you give is a link, doc, or something, it'll be great help to me.

I'll wait for your any comments or answers. :)

Canet Robern
  • 1,049
  • 2
  • 11
  • 28

1 Answers1

3

First solution you can add one more option tag for default value

Html Code

<div ng-app="MyApp">
    <div ng-controller="MyCtrl">
        <select ng-options="opt as opt for opt in testOpt"
                data-ng-model="resultOpt"
                data-ng-change="checkResultOpt(resultOpt)">
        <option value=''>Choose Category </option>
        </select>

    </div>
</div>

Controller Code

 var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.testOpt = [
        'ID',
        'Name',
        'Email',
        'Address'
    ];
    $scope.resultOpt = '';
}]);

Working code

Second Solution : you just add one more item in your array list after get from http call

Html Code

<div ng-app="MyApp">
    <div ng-controller="MyCtrl">
        <select ng-options="opt as opt for opt in testOpt"
                data-ng-model="resultOpt"
                data-ng-change="checkResultOpt(resultOpt)">
        </select>

    </div>
</div>

Controller Code :

var MyApp = angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.testOpt = [
        'ID',
        'Name',
        'Email',
        'Address'
    ];
    $scope.testOpt.splice(0, 0, 'Choose Category');
    $scope.resultOpt = 'Choose Category';
}]);

Working Code

hope this will help you

Manoj Patidar
  • 1,171
  • 2
  • 11
  • 29
  • 1
    Your fiddle looks almost near to my purpose. What I really want is when I select a category, default value have to disappear. But thank you for give me some hints! – Canet Robern Sep 29 '17 at 04:56