AngularJS null value for select

后端 未结 9 913
攒了一身酷
攒了一身酷 2021-02-01 14:32

I couldn\'t find an elegant way for setting null values with a

相关标签:
9条回答
  • 2021-02-01 14:59

    the only way you can achieve that is by using a onchange event and restoring the object as initialized any other attempt to set the selected to null will remove the property from the object.

    $scope.setValue=function(val){
      if($scope.obj.selected=="null")
         $scope.obj ={"selected":null};
    }
    
    <select ng-change="setValue()" ng-model="obj.selected">
      <option value=null ng-click="obj.selected=null">Unknown</option>
      <option value="1">Yes</option>
      <option value="0">No</option>
    </select>
    

    this is a bad idea, you should always have values in your model instead of playing around with null and undefined

    0 讨论(0)
  • 2021-02-01 15:02

    This should work for you:

    Controller:

      function MyCntrl($scope) {
        $scope.obj ={"selected":null};
        $scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}]
      }
    

    Template:

      <div ng-controller="MyCntrl">
    
        <select ng-model="obj.selected"
                ng-options="value.id as value.value for value in objects">
                <option value="">Unknown</option>
        </select>
    
    <br/>
         {{obj}}
      </div>
    

    Working plnkr

    You should use ng-options with select.

    0 讨论(0)
  • 2021-02-01 15:02

    Without the possibility of using ng-options I present another fix.

    I've been battling this a couple of months now, using solutions presented on this question and I don't know how nobody posted this:

    <option value="null"></option>
    

    This should work on Angular 1.6 and above for sure when you are using ng-repeat for options instead of ng-options.

    It's not ideal but since we are used to work on legacy code this simple fix could save your day.

    0 讨论(0)
提交回复
热议问题