Search code examples
javascriptangularjsangularjs-scopeangularjs-ng-repeat

How to get id in dropdown and also set default value on top


I have the code below and I want card_id but it shows null. How can I get the id and is_default card on top? when I use ng-click, it shows the result below. I want to get the selected 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>

result:

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

Solution

  • Use ngOptions (that page has more examples) to set the options for the select list and ng-bind to display the card_id in the DOM. It also uses functional approach to set the currentcard using Array.prototype.find(). See the example below:

    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>