How to have a default option in Angular.js select box

后端 未结 23 1590
悲哀的现实
悲哀的现实 2020-11-22 06:04

I have searched Google and can\'t find anything on this.

I have this code.


  
  
option = {{data.selectedOption}}

plnkr.co

Official documentation about HTML SELECT element with angular data-binding.

Binding select to a non-string value via ngModel parsing / formatting:

(function(angular) {
  'use strict';
angular.module('nonStringSelect', [])
  .run(function($rootScope) {
    $rootScope.model = { id: 2 };
  })
  .directive('convertToNumber', function() {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        ngModel.$parsers.push(function(val) {
          return parseInt(val, 10);
        });
        ngModel.$formatters.push(function(val) {
          return '' + val;
        });
      }
    };
  });
})(window.angular);


  
{{ model }}

plnkr.co

Other example:

angular.module('defaultValueSelect', [])
 .controller('ExampleController', ['$scope', function($scope) {
   $scope.availableOptions = [
     { name: 'Apple', value: 'apple' }, 
     { name: 'Banana', value: 'banana' }, 
     { name: 'Kiwi', value: 'kiwi' }
   ];
   $scope.data = {selectedOption : $scope.availableOptions[1].value};
}]);


  

jsfiddle

提交回复
热议问题