AngularJS select creates option with value “? object:null ?” and doesn't use empty default option when bound to null

前端 未结 4 789
你的背包
你的背包 2021-01-04 05:21

Here\'s what the code looks like


                        
    
提交评论

  • 2021-01-04 06:17

    Update 3/29/2017:

    As Jorge Rodrigues dos Santos stated, this should be handled in a different way for newer versions of angular. Below is taken from the current documentation for angular 1.6.3

    Optionally, a single hard-coded element, with the value set to an empty string, can be nested into the element. This element will then represent the null or "not selected" option. See example below for demonstration.

    https://docs.angularjs.org/api/ng/directive/select


    Angular is creating a new option to represent the null value. It didn't find one of the options you provided in the HTML.

    To bind to null, set the value="null" on the first option

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

    http://plnkr.co/edit/kzPVu4hiMcP6wA6crGYt?p=preview

    0 讨论(0)
  • 2021-01-04 06:22

    The accepted answer didn't work for me because my property could be blank, null, or undefined. If you are using version 1.3+ then you can use a getterSetter to coerce the value to blank.

    I was dealing with string values. You'll have to handle 0 or other valid falsy values in the function as well.

    $scope.nullableIntCoerced = function(n) {
        return arguments.length ? ($scope.nullableInt = n) : ($scope.nullableInt || "");
    }
    
    <select ng-model="nullableIntCoerced" ng-model-options="{getterSetter:true}">
        <option value=""></option>
        ...
    

    https://code.angularjs.org/1.3.20/docs/api/ng/directive/ngModel

    0 讨论(0)
  • 2021-01-04 06:24

    For more recent versions of Angularjs use <option value=""> - </option> for the null value

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