没有将 ng-options select 设置为预定义的 ng-model 结果

not setting the ng-options select to the predefined ng-model results

我输入了一个值,并希望在 select 下拉列表中预select。复杂的是模型是一个对象而不是一个简单的字符串。我试过使用 track by 但它似乎没有解决问题...也许你能帮忙?

让我们假设控制器加载时 javascript 中的模型:

$scope.condition = {name: 'blah', value: '{"id":2,"value":"Monthly Flyer"}' }
$scope.options = [
    {"id":1,"value":"Winter Catalog"},
    {"id":2,"value":"Monthly Flyer"},
    {"id":3,"value":"Sample Catalog"},
    {"id":4,"value":"Senior Living"},
    ...]

请注意第二个与第一个看起来是同一个对象...但是,从技术上讲,它会有不同的对象引用,所以

angular.toJson($scope.condition) === angular.toJson(options[1])true$scope.condition === options[1]false

这是代码

<select class="form-control" ng-model="condition.value"
        ng-options="opt as (opt.value + ' [' + opt.id + ']')
            for opt in options.picklistOptions track by opt.id"></select>

为什么你认为它没有加载?

试试这个:

angular.module('app', [])
  .controller('Controller', ['$scope', function($scope) {
    
  $scope.listOptions = [
    {id:1,value:"Winter Catalog"},
    {id:2,value:"Monthly Flyer"},
    {id:3,value:"Sample Catalog"},
    {id:4,value:"Senior Living"}
  ];
    
}]);
<html ng-app="app">
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">  </script>
   </head>
<body ng-controller="Controller">
  
  <select class="form-control" ng-model="obj_options" ng-options="item as item.value for item in listOptions"></select>
  
  <span>{{obj_options.value}}</span>
  
</body>
</html>

嗯,我不确定你想做什么,但我认为你有一个对象保存在某处并且你想 select 基于此的 <option>

那么,如果我是对的,你只是错误地将 ng-model 放置为 condition.value 而不是 condition.

看到它有效:

(function() {
  "use strict";
  angular.module('app', [])
    .controller('mainCtrl', function($scope) {
      $scope.options = {};
      $scope.options.picklistOptions = [  
         {  
            "id":1,
            "value":"Winter Catalog"
         },
         {  
            "id":2,
            "value":"Monthly Flyer"
         },
         {  
            "id":3,
            "value":"Sample Catalog"
         },
         {  
            "id":4,
            "value":"Senior Living"
         }
      ];

      $scope.condition = {
        "id":2,
        "value":"Monthly Flyer"
      };         
    });
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <select class="form-control" ng-model="condition" ng-options="opt as (opt.value + ' [' + opt.id + ']') for opt in options.picklistOptions track by opt.id"></select>
  <hr>
  <span ng-bind="condition | json"></span>
</body>

</html>