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

后端 未结 27 1203
感动是毒
感动是毒 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 09:05

    Selecting an item in ng-options can be a bit tricky depending on how you set the data source.

    After struggling with them for a while I ended up making a sample with most common data sources I use. You can find it here:

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

    Now to make ng-options work, here are some things to consider:

    1. Normally you get the options from one source and the selected value from other. For example:
      • states :: data for ng-options
      • user.state :: Option to set as selected
    2. Based on 1, the easiest/logical thing to do is to fill the select with one source and then set the selected value trough code. Rarely would it be better to get a mixed dataset.
    3. AngularJS allows select controls to hold more than key | label. Many online examples put objects as 'key', and if you need information from the object set it that way, otherwise use the specific property you need as key. (ID, CODE, etc.. As in the plckr sample)
    4. The way to set the value of the dropdown/select control depends on #3,

      • If the dropdown key is a single property (like in all examples in the plunkr), you just set it, e.g.: $scope.dropdownmodel = $scope.user.state;
      • If you set the object as key, you need to loop trough the options, even assigning the object will not set the item as selected as they will have different hashkeys, e.g.:

        for (var i = 0, len = $scope.options.length; i < len; i++) {
          if ($scope.options[i].id == savedValue) { // Your own property here:
            console.log('Found target! ');
            $scope.value = $scope.options[i];
            break;
          }
        }
        

    You can replace savedValue for the same property in the other object, $scope.myObject.myProperty.

提交回复
热议问题