0

I am using AngularJS and what i want to do is to use a select to select an item, but then have access to an array that can produce other information.

Eg:

<select name="manufacturer" id="manufacturer" ng-model="manufacturer" class="form-control">
    <option value="{{ A[0] }}">{{ A[0] }}</option>
    <option value="{{ B[0] }}">{{ B[0[ }}</option>
    <option value="{{ C[0] }}">{{ C[0] }}</option>
</select>

// NAME, SKU, PRICE, WEIGHT

$scope.A = ["Ferarri","FER1",128000,1.5];
$scope.B = ["Ford","FOR1",13000,1];
$scope.C = ["Renault","REN1",13000,1];

So, I can easily print the 'name' in the select for the user to know what they're selecting, but once selected, I want to have full use of that array. So, if the user chooses 'Ford' I want to be able to have something like $scope.car[2] for the price of the car, whatever their selection might be which would give me '13000'.

What would be the best way to do this?

Thanks.

1
  • you really should consider switching to objects instead of arrays whenever possible while using angular. then, you can pass an array of car objects to ng-options, and select one easily. also, having these as objects would make working with them make more sense; i.e. $scope.car.price is much clearer than $scope.car[2]. Commented Aug 15, 2015 at 19:38

1 Answer 1

3

Something like this will give you access to the entire object:

$scope.cars = [
  {name: "Ferarri", short: "FER1", price: 128000, num: 1.5}
  {name: "Ford", short: "FOR1", price: 13000, num: 1}
  {name: "Renault", short: "REN1", price: 13000, num: 1}
]

<select ng-model="car" ng-options="car as car.name for car in cars"></select>

Then you can use it in your templates like so:

<h1>{{car.price}}</h1>

I'm using ng-options to achieve this which is very flexibel, have a look here in the official documentation: https://docs.angularjs.org/api/ng/directive/ngOptions

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for taking the time to answer. I am now using an object rather than an array. I have populated the selects and all works well. The issue is when i choose Ferrari in the dropdown, I can use {{ ferrari.name }} but anything else gives me nothing i.e {{ ferrari.price }}
@devon93 Use car.price not ferrari.price, since car is the object you're accessing and not "ferrari", "ferrari" is only a name property.
Ah yeah sorry thats what i meant.
@devon93 Are you trying to use the value in your template or in the controller?
@devon93 I forgot the ng-model sorry, I updated answer, now it should work.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.