通过Id Angularjs下拉选择轨道

问题描述 投票:0回答:1

我有以下数据在我的控制器中下拉。

 $scope.groups={{"gpId": 3, "name" :"Tom"}, {"gpId": 32, "name" :"Helen"},{"gpId": 9, "name" :"Amy"}

 $scope.user=
 {
   tkId: 32;
   place: NW
  }

在我的HTML中,我有以下选择

   <select ng-model="user.tkId" ng-options="a.gpId as a.name for a in groups track by a.gpId></select>

当我运行这个时,我会选择Helen,但是当我想从下拉菜单中更改选择时,它不会让我失望。请让我知道如何更改它以选择其他选项,以便我可以在需要时保存。谢谢

javascript jquery angularjs
1个回答
0
投票

以下代码段有效。

首先,像[{}, {}]这样编写一个对象数组

It's written in the angular docs认为track byas不应该一起使用。

不要在同一个表达式中使用select astrack by。它们不是为了共同努力而设计的。

<body ng-app="selectExample">
  <script>
    angular.module('selectExample', [])
      .controller('ExampleController', ['$scope', function($scope) {
        $scope.groups = [{
          "gpId": 3,
          "name": "Tom"
        }, {
          "gpId": 32,
          "name": "Helen"
        }, {
          "gpId": 9,
          "name": "Amy"
        }];
        $scope.user = {
          tkId: 32,
          place: 'NW'
        };
      }]);
  </script>
  <div ng-controller="ExampleController">
    <label>Group:
      <select ng-model="user.tkId" ng-options="group.gpId as group.name for group in groups"></select>
    </label>
    <br/> {{user.tkId}}
  </div>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.