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

后端 未结 27 829
感动是毒
感动是毒 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条回答
  • 2020-11-22 08:59

    To send a custom value called my_hero to the server using a normal form submit:

    JSON:

    "heroes": [
      {"id":"iron", "label":"Iron Man Rocks!"},
      {"id":"super", "label":"Superman Rocks!"}
    ]
    

    HTML:

    <select ng-model="hero" ng-options="obj.id as obj.label for obj in heroes"></select>
    <input type="hidden" name="my_hero" value="{{hero}}" />
    

    The server will receive either iron or super as the value of my_hero.

    This is similar to the answer by @neemzy, but specifying separate data for the value attribute.

    0 讨论(0)
  • 2020-11-22 08:59

    For me the answer by Bruno Gomes is the best answer.

    But actually, you need not worry about setting the value property of select options. AngularJS will take care of that. Let me explain in detail.

    Please consider this fiddle

    angular.module('mySettings', []).controller('appSettingsCtrl', function ($scope) {
    
        $scope.timeFormatTemplates = [{
            label: "Seconds",
            value: 'ss'
        }, {
            label: "Minutes",
            value: 'mm'
        }, {
            label: "Hours",
            value: 'hh'
        }];
    
    
        $scope.inactivity_settings = {
            status: false,
            inactive_time: 60 * 5 * 3, // 15 min (default value), that is, 900 seconds
            //time_format: 'ss', // Second (default value)
            time_format: $scope.timeFormatTemplates[0], // Default seconds object
        };
    
        $scope.activity_settings = {
            status: false,
            active_time: 60 * 5 * 3, // 15 min (default value), that is,  900 seconds
            //time_format: 'ss', // Second (default value)
            time_format: $scope.timeFormatTemplates[0], // Default seconds object
        };
    
        $scope.changedTimeFormat = function (time_format) {
            'use strict';
    
            console.log('time changed');
            console.log(time_format);
            var newValue = time_format.value;
    
            // do your update settings stuffs
        }
    });
    

    As you can see in the fiddle output, whatever you choose for select box options, it is your custom value, or the 0, 1, 2 auto generated value by AngularJS, it does not matter in your output unless you are using jQuery or any other library to access the value of that select combo box options and manipulate it accordingly.

    0 讨论(0)
  • 2020-11-22 08:59

    It is always painful for developers to with ng-options. For example: Getting an empty/blank selected value in the select tag. Especially when dealing with JSON objects in ng-options, it becomes more tedious. Here I have done some exercises on that.

    Objective: Iterate array of JSON objects through ng-option and set selected first element.

    Data:

    someNames = [{"id":"1", "someName":"xyz"}, {"id":"2", "someName":"abc"}]
    

    In the select tag I had to show xyz and abc, where xyz must be selected without much effort.

    HTML:

    <pre class="default prettyprint prettyprinted" style=""><code>
        &lt;select class="form-control" name="test" style="width:160px"    ng-options="name.someName for name in someNames" ng-model="testModel.test" ng-selected = "testModel.test = testModel.test || someNames[0]"&gt;
    &lt;/select&gt;
    </code></pre>
    

    By above code sample, you might get out of this exaggeration.

    Another reference:

    0 讨论(0)
  • 2020-11-22 09:00

    The correct answer to this question has been provided by user frm.adiputra, as currently this seems to be the only way to explicitly control the value attribute of the option elements.

    However, I just wanted to emphasize that "select" is not a keyword in this context, but it is just a placeholder for an expression. Please refer to the following list, for the definition of the "select" expression as well as other expressions that can be used in ng-options directive.

    The use of select as it is depicted in the question:

    ng-options='select p.text for p  in resultOptions'
    

    is essentially wrong.

    Based on the list of expressions, it seems that trackexpr may be used to specify the value, when options are given in an array of objects, but it has been used with grouping only.


    From AngularJS' documentation for ng-options:

    • array / object: an expression which evaluates to an array / object to iterate over.
    • value: local variable which will refer to each item in the array or each property value of object during iteration.
    • key: local variable which will refer to a property name in object during iteration.
    • label: The result of this expression will be the label for element. The expression will most likely refer to the value variable (e.g. value.propertyName).
    • select: The result of this expression will be bound to the model of the parent element. If not specified, select expression will default to value.
    • group: The result of this expression will be used to group options using the DOM element.
    • trackexpr: Used when working with an array of objects. The result of this expression will be used to identify the objects in the array. The trackexpr will most likely refer to the value variable (e.g. value.propertyName).
    0 讨论(0)
  • 2020-11-22 09:01

    How the value attributes gets its value:

    • When using an array as datasource, it will be the index of the array element in each iteration;
    • When using an object as datasource, it will be the property name in each iteration.

    So in your case it should be:

    obj = { '1': '1st', '2': '2nd' };
    
    <select ng-options="k as v for (k,v) in obj"></select>
    
    0 讨论(0)
  • 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:

    <select
        ng-model="selectedCountry"
        ng-options="obj.name for obj  in countries">
    </select>
    

    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)
    
    0 讨论(0)
提交回复
热议问题