How do I set the value property in AngularJS' ng-options?

后端 未结 27 1283
感动是毒
感动是毒 2020-11-22 08:17

Here is what seems to be bothering a lot of people (including me).

When using the ng-options directive in AngularJS to fill in the options for a &

27条回答
  •  借酒劲吻你
    2020-11-22 08:56

    Run the code snippet and see the variations. Here is note for quick understanding

    1. Example 1(Object selection):- ng-option="os.name for os in osList track by os.id". Here track by os.id is important & should be there and os.id as should NOT have before os.name.

      • The ng-model="my_os" should set to an object with key as id like my_os={id: 2}.
    2. Example 2(Value selection) :- ng-option="os.id as os.name for os in osList". Here track by os.id should NOT be there and os.id as should be there before os.name.

      • The ng-model="my_os" should set to a value like my_os= 2

    Rest code snippet will explain.

    angular.module('app', []).controller('ctrl', function($scope, $timeout){
      
      //************ EXAMPLE 1 *******************
      $scope.osList =[
        { id: 1, name :'iOS'},
        { id: 2, name :'Android'},
        { id: 3, name :'Windows'}
      ]
      $scope.my_os = {id: 2};
      
      
      //************ EXAMPLE 2 *******************
      $timeout(function(){
        $scope.siteList = [
              { id: 1, name: 'Google'},
              { id: 2, name: 'Yahoo'},
              { id: 3, name: 'Bing'}
            ];
       }, 1000);
        
        $scope.my_site = 2;
      
        $timeout(function(){
          $scope.my_site = 3;
        }, 2000);
    })
    fieldset{
      margin-bottom: 40px;
      }
    strong{
      color:red;
      }
    
    
    
    Example 1 (Set selection as object) {{my_os}}
    Example 2 (Set selection as value. Simulate ajax) {{my_site}}

提交回复
热议问题