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

后端 未结 27 851
感动是毒
感动是毒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 09:01

    Like many said before, if I have data something like this:

    countries : [
                  {
                     "key": 1,
                     "name": "UAE"
                 },
                  {
                      "key": 2,
                      "name": "India"
                  },
                  {
                      "key": 3,
                      "name": "OMAN"
                  }
             ]
    

    I would use it like:

    
    

    In your Controller you need to set an initial value to get rid of the first empty item:

     $scope.selectedCountry = $scope.countries[0];
    
     // You need to watch changes to get selected value
     $scope.$watchCollection(function() {
       return $scope.selectedCountry
     }, function(newVal, oldVal) {
         if (newVal === oldVal) {
           console.log("nothing has changed " + $scope.selectedCountry)
         } 
         else {
           console.log('new value ' + $scope.selectedCountry)
         }
     }, true)
    

提交回复
热议问题