如何在下拉列表中获取ID并在顶部设置默认值

时间:2016-12-27 21:03:39

标签: javascript angularjs angularjs-scope angularjs-ng-repeat

我有以下代码,我想 card_id ,但它显示 null 。如何在顶部获取 id is_default 卡?当我使用ng-click时,它会显示下面的结果。我想获得所选的card_id。

<select ng-model="approvedinvoicesCtrl.currentcard.card_id" >
    <option ng-value="item.card_id"  
        ng-repeat="item in approvedinvoicesCtrl.current_job.cards" 
        ng-selected="item.is_default">{{item.brand +'      '+ item.last_digits}}
    </option>
</select>

结果:

card_id: "",
charge_description: "ff", 
charge_type: "Credit Card Payment"

2 个答案:

答案 0 :(得分:0)

您需要使用ng-initng-options指令:

<select ng-init="somethingHere = options[1]" 
        ng-model="somethingHere" 
        ng-options="option for option in options">
</select>

使用ng-init设置您想要的默认值

答案 1 :(得分:0)

使用ngOptions(该页面包含更多示例)设置选择列表的选项,并使用ng-bind在DOM中显示 card_id 。它还使用函数方法使用Array.prototype.find()设置当前卡。请参阅以下示例:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.approvedinvoicesCtrl = {
      current_job: {
        cards: [{
          card_id: 1,
          brand: "BMW",
          last_digits: "Z3",
          is_default: false
        }, {
          card_id: 2,
          brand: "Mercedes",
          last_digits: "713",
          is_default: true
        }, {
          card_id: 3,
          brand: "Audi",
          last_digits: "Q4",
          is_default: false
        }]
      }
    };
    //set the model/default selected item
    $scope.approvedinvoicesCtrl.currentcard = $scope.approvedinvoicesCtrl.current_job.cards.find(CardIsDefault);
    $scope.log = function() {
      console.log('card_id: ', $scope.approvedinvoicesCtrl.currentcard.card_id);
    };
  });

function CardIsDefault(card) {
  return card.is_default;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div>Selected brand: <span ng-bind="approvedinvoicesCtrl.currentcard.brand"></span>
  </div>
  <div>Selected Id: <span ng-bind="approvedinvoicesCtrl.currentcard.card_id"></span>
  </div>
  <select ng-options="item.brand+' '+item.last_digits for item in approvedinvoicesCtrl.current_job.cards" ng-model="approvedinvoicesCtrl.currentcard"></select>
  <button ng-click="log();">show card_id</button>
</div>