Skip to content Skip to sidebar Skip to footer

Angularjs Null Value For Select

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

Solution 1:

This should work for you:

Controller:

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

Template:

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

Working plnkr

You should use ng-options with select.

Solution 2:

You can use the ngOptions directive on the select. According to the documentation:

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

<selectng-model="obj.selected"ng-options="key as label for (key, label) in ['No', 'Yes']"><optionvalue="">Unknown</option></select>

It's obviously a better idea to define the options list directly in the controller.

Solution 3:

Try using ng-options instead of manually creating tags, as in this example, lightly-edited from the Angular docs:

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

The operative parts here are lines 17, defining a 'colors' object, and the ng-options attributes iterating over those colors to create options.

Solution 4:

If you REALLY want to use null, see below. You need to use ng-options and let Angular handle the mapping:

<!doctype html><htmllang="en"><head><metacharset="UTF-8"><title>Color selector</title><scriptsrc="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular.min.js"></script></head><bodyng-app=""><script>functionMyCntrl($scope) {
    $scope.obj ={"selected":null};
    $scope.objStates = [{key:"Unknown", value:null}, {key:"Yes", value:1}, {key:"No", value:0}]

    $scope.$watch('obj.selected', function(newVal){
      console.log(newVal);
    })
  }
  </script><divng-controller="MyCntrl"><selectng-model="obj.selected"ng-options="state.value as state.key for state in objStates"></select><br/>
     {{obj}}
  </div></body></html>

Solution 5:

I ran into the same Problem but could not solve it via 'ng-options'. My solution is:

module.directive('modelToNull', [function () {
    return {
        scope: {
            check: "&modelToNull"
        },
        require: 'ngModel',
        link: function ($scope, element, attrs, ngModelController) {
            ngModelController.$parsers.push(function (value) {
                return value == null || $scope.check({value: value}) ? null : value;
            });
        }
    };
}]);

You can use it like this:

<select ng-model="obj.selected" model-to-null="value == 'null'">
  <option value="null">Unknown</option>
  <option value="1">Yes</option>
  <option value="0">No</option>
</select>

Post a Comment for "Angularjs Null Value For Select"