Search code examples
javascriptangularjscakephpangularjs-scopeangularjs-ng-repeat

Select multiple display names instead of IDs using AngularJS


I have a multiple select like this :

<select ng-model="listProds" multiple>
  <option value="10">product 1</option>
  <option value="25">product 2</option>
  <option value="35">product 3</option>
  <option value="48">product 4</option>
</select>

The values are the Ids for these products ( and this selectbox is generated using PHP )

& I've got this simple code in my app.js file :

var app = angular.module('myapp', []);
app.controller("PurchasesController", function($scope) {

    // Init products Array
    $scope.listProds = [];

});

When I display the listProds like this {{ listProds }}, I get an array containing the current selected items, but it only shows the Ids like this if I select all of them ["10","25","35","48"].

<fieldset ng-show="listProds.length > 0">
    <div data-ng-repeat="p in listProds track by $index">
        {{ p }} <!– Or –> {{ listProds[$index] }}
        <input type="text" name="pr{{ listProds[$index] }}" />
        <input type="text" name="qt{{ listProds[$index] }}" />
    </div>
</fieldset>

This code generate two text boxes to enter the Price and Quantity for each Product in selected from the selectbox. So instead of using {{ p }} or {{ listProds[$index] }} and displaying the Product Id, I want to display there the Product name.

Thank you in advance.


Solution

  • You can create two lists: one for all your products and a separate list for the selected products:

    $scope.listProds = [
      { key: 10, value: 'Product 1' },
      { key: 25, value: 'Product 2' },
      { key: 35, value: 'Product 3' },
      { key: 45, value: 'Product 4' }
    ];
    
    $scope.selectedProds = [];
    

    Now in your markup, instead of writing out each option in your select manually, you can use ng-options to generate your options. Using this approach, you are basically saying that each option is an object, and you want to use the objects value as the display name.

     <select ng-model="selectedProds" ng-options="prod.value for prod in listProds" multiple>
    

    Now your $scope.selectedProds array will contain the product objects, and not just they keys. So now you can display the name easily:

    <fieldset ng-show="selectedProds.length > 0">
      <div data-ng-repeat="p in selectedProds track by $index">
        {{ p.value }}
        <input type="text" name="pr{{ selectedProds[$index] }}" />
        <input type="text" name="qt{{ selectedProds[$index] }}" />
      </div>
    </fieldset>
    

    Not sure what your want the name attribute of the inputs to be, but I hope you get the idea.