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
    }
});    
3
  • 2
    app.controller("myCtrl"), function($scope) {... This is a typo, right? Should be app.controller("myCtrl", function($scope) { Commented Feb 17, 2016 at 21:10
  • And also rates.objectType is not correct is it? You need the value of objectType. Like rates[objectType] Commented Feb 17, 2016 at 21:13
  • @SzabolcsDézsi, yes it was a typo (corrected). Thanks Commented Feb 17, 2016 at 21:19

2 Answers 2

2

You can do it like this

{{h * rates[objectType] || 0}}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.