Michael Michael - 1 year ago 63
AngularJS Question

How Do I Structure Multiple Select Options Over an Array of Objects in Angular

I have an super big array similar to this:

$scope.providers = [{
providerName: 'John Doe',
colors: 1,
itemQuantity: 100,
item: 'pen',
price: 2,5
providerName: 'John Doe',
colors: 1,
itemQuantity: 200,
item: 'pen',
price: 2
providerName: 'John Doe',
colors: 3,
itemQuantity: 400,
item: 'clock',
price: 10
providerName: 'Jane Doe',
colors: 1,
itemQuantity: 50,
item: 'bag',
price: 15

Im building a proposal maker, so I need our business employees to select which provider option they'll be using. (For you to understand these providers just put a logo on our items, and that array of objects is really a list of the prices they charge by quantity of colors, type of item and quantity of items)

The thing is, I want to create a select input with options to first choose which provider we will be using, let's say we settle with John Doe. Then I want a select input to choose the quantity of colors, but will only offer those that John Doe offers. Then I need another input which will let me choose the type of items that John Doe works for that quantity of colors... and so on
Finally I'd like to get the price for all that options

I'm getting quite lost on how to build this on angularjs (version 1.5.8)

Also something tells me I should order my data in a better way than that huge array.

Any suggestion on both issues?


Answer Source

Basically you set it up to have the comboboxes be based off the previous ones (excuse the silly html, it was for demo purposes):

Working Plnkr

<body ng-controller="MainCtrl"> 
    <select ng-model="selectedProvider" ng-options="p.providerName as p.providerName for p in providers | unique:'providerName'">{{p}} </select>    
    Selected Provider: {{selectedProvider}}
    Number of Colors:   
    <select ng-model="selectedNumber" ng-options="n.colors as n.colors for n in providers | filter : {providerName:selectedProvider } | unique:'colors' "> </select>    
    Selected Number: {{selectedNumber}}
    <select ng-model="selectedItem" ng-options="i.item as i.item for i in providers | unique:'item'  | filter : {providerName:selectedProvider, colors: selectedNumber}"> </select> 
    Selected Item: {{selectedItem}}
    Distinct Prices: 
    <div ng-repeat="p in providers | filter :  {providerName:selectedProvider, colors: selectedNumber, item: selectedItem}">

enter image description here

You'll have to make sure you include 'angular.filter' dependency and the .js file at the top of the plnkr. You may also have to make sure the filtering matches whole words, and not just parts, but this should be more than enough to get you started.