简体   繁体   中英

setting selected value as undefined in angualrjs

I am using angularjs ng-options and ng-model directives in my view to set the select option and get notified when dropdown option is selected or changed. I am also adding extra empty option so that user can deselect this and for that I want value in ng-model expression to be undefined. Is there any way to do that ? I tried adding value=="{{undefined}}" but that takes out the empty option totally.

Here is the plunker example where if I select the empty option then data.model should be undefined but here it is coming as null.

https://plnkr.co/edit/d9Jzs4YgqpWHbOxonwa3?p=preview

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-select-ngvalue-production</title>


  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="app.js"></script>




    </head>
    <body ng-app="ngvalueSelect">
      <div ng-controller="ExampleController">
      <form name="myForm">
        <label for="ngvalueselect"> ngvalue select: </label>
        <select size="6" name="ngvalueselect" ng-model="data.model" multiple>

          <option label='' value="{{undefined}}"/>
          <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>

        </select>
      </form>
      <hr>
      <pre>model = {{data.model === undefined | json}}</pre><br/>
    </div>
    </body>
    </html>

Corresponding app.js is

(function(angular) {
  'use strict';
angular.module('ngvalueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     model: null,
     availableOptions: [
          {value: 'myString', name: 'string'},
          {value: 1, name: 'integer'},
          {value: true, name: 'boolean'},
          {value: null, name: 'null'},
          {value: {prop: 'value'}, name: 'object'},
          {value: ['a'], name: 'array'}
     ]
    };
 }]);
})(window.angular);

Thanks

There are two issues with your code:

  1. Your dropdown allows multiple select thanks to the multiple attribute. This means that your model stores array of selections. The value you are looking for is one of the elements of the array, but in your code you are comparing undefined to the whole array.
  2. Your additional option should use ng-value instead of value attribute. You don't need to write is as separate option, you can add it to availableOptions object (as {value: undefined, name: ''} ).

Here is the updated plunker: https://plnkr.co/edit/RXUlW6P7DX2wPZOazwe8?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM