ng-select使用ng-repeat设置所选选项

时间:2016-08-21 19:51:56

标签: angularjs angularjs-ng-repeat angularjs-select

我无法通过选择框显示选项已被选中,即使看起来应该是这样。我有一个对象数组,我有一个属性,每个显示为真或假。

<div ng-controller="testCtrl">
 <table class="table table-striped table-bordered table-hover">
   <tr ng-repeat="(key, data) in activePlans.details">
     <td>{{ data.name }}</td>
       <td class=""> {{ data.id }}
         <select  ng-model="program" ng-change="">
            <option ng-repeat="program in data.programs" ng-selected="{{ program.selected == true }}" selected=""  
              value="{{ program.product_id }}">{{ program.name }}</option>
         </select>
      </td>
    </tr>
  </table> 
</div>

JavaScript:

var app = angular.module("myApp", []);

app.controller('testCtrl', ['$scope', function($scope) {

  console.log('sdfsdf');
  $scope.activePlans = {};
  $scope.activePlans.details = {
    "1": {
      "id": 1,
      "name": "breakfast",
      "product_id": 1,
      "programs": [{
        "product_id": 1,
        "name": "AA Plan",
        "selected": true,
        "selectedOption": 1
      }, {
        "product_id": 3,
        "name": "SS Plan",
        "selected": false,
        "selectedOption": 0
      }, {
        "product_id": 4,
        "name": "PP Plan",
        "selected": false,
        "selectedOption": 0
      }]

    },
    "2": {
      "id": 2,
      "name": "lunch",
      "product_id": 3,
      "programs": [{
        "product_id": 1,
        "name": "AA Plan",
        "selected": false,
        "selectedOption": 0
      }, {
        "product_id": 3,
        "name": "SS Plan",
        "selected": true,
        "selectedOption": 1
      }, {
        "product_id": 4,
        "name": "PP Plan",
        "selected": false,
        "selectedOption": 0
      }]
    },
    "3": {
      "id": 3,
      "name": "dinner",
      "product_id": 4,
      "programs": [{
        "product_id": 1,
        "name": "AA Plan",
        "selected": false,
        "selectedOption": 0
      }, {
        "product_id": 3,
        "name": "SS Plan",
        "selected": false,
        "selectedOption": 0
      }, {
        "product_id": 4,
        "name": "PP Plan",
        "selected": true,
        "selectedOption": 1
      }]
    },
    "4": {
      "id": 4,
      "name": "4th meal",
      "product_id": 5,
      "programs": [{
        "product_id": 1,
        "name": "AA",
        "selected": false,
        "selectedOption": 0
      }, {
        "product_id": 3,
        "name": "SS Plan",
        "selected": false,
        "selectedOption": 0
      }, {
        "product_id": 4,
        "name": "PP Plan",
        "selected": false,
        "selectedOption": 0
      }]
    }
  }
  console.log($scope.activePlans.details);

}]);

以下是Fiddle

1 个答案:

答案 0 :(得分:2)

更新您的<option>标记,如下所示:

<option ng-repeat="program in data.programs" ng-selected="program.selected == true" value="{{ program.product_id }}">{{ program.name }}</option>

Updated Fiddle