3

I'm trying to calculate a rate automatically when a user gives the inputs.

A user can select one of the 3 items in the "types" list, and it should input the result of multiplying the multiplier (input), and the chosen object.

I tried a bunch of things (including interpolating on the controller), but can't seem to retrieve the rate in the object whose name is the same as the ng-model.

What can I do here?

HTML:

<div ng-app="myApp" ng-controller="myCtrl">

    <label>Input a multiplier</label></br>
    <input ng-model="h" /></br>

    <label>Which object do you want?</label></br>
    <select ng-model="objectType" ng-options="j for j in types"></select></br>

    <h1> {{ h * rates.objectType }} </h1>
</div>

Angularjs:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

    $scope.types = ["obj1", "obj2", "obj3"];
    $scope.rates = {
        obj1: 3,
        obj2: 5,
        obj3: 7
    }
});    

2 Answers2

2

Use [] object notation for variable property names

{{ h * rates[objectType] || 0 }}

The || 0 is an assumption that you want to show zero when either of the other values is undefined

charlietfl
  • 170,828
  • 13
  • 121
  • 150
2

You can do it like this

{{h * rates[objectType] || 0}}
Guilherme Ferreira
  • 2,209
  • 21
  • 23