WakaChewbacca WakaChewbacca - 4 months ago 11
AngularJS Question

Updating controller variable upon ng-option being selected

I am currently trying to set a variable in a controller upon another value being selected via

ng-options
. For example, if one selected from
Companies
according to
title
then
myValue
will be set to the corresponding
id
of a specific company. The following is the HTML snippet:

<select multiple="" class="form-control" ng-model="myValue"
ng-options="d.title for d in Companies"></select>


<select multiple="" class="form-control">
<option ng-placeholder="{{myValue}}"></option>
</select>


And my
Company
,
Companies
, and
myValue
in the controller:

function Company(title, last, pw, id) {
this.title = title;
this.id = id;
}
$scope.Companies = [];

$scope.myValue = '';


And here is the fucntion that seeds the
Companies
array:

$scope.getValues = function () {
$http.get('/route/to/names')
.success(function (data, status, headers, config) {
for (var i = 0; i < data.length; i++) {
$scope.Companies.push(new Company(data[i]['Title'],data[i]['ID']));
}
})
};


The purpose behind the program is to further fetch data from a database according to the selected
Company
. The reason why I have
myValue
set as an option on the page is to determine if the action is achieved. Any advice as to how to solve this or similar problems would be greatly appreciated! Thanks!

Answer
d.id as d.title for d in Companies 
  • Make sure to use the correct casing, as you have title and id lower-case in your Company constructor but proper cased in your for loop