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

后端 未结 27 1215
感动是毒
感动是毒 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

    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.

提交回复
热议问题