Reputation: 131
I am trying to make some currency exchange system SPA based on AngularJS.
There should be several inputs that get currency data from json (with ng-repeat) and convert currency rate depending on active input value.
{
"currencies": [
{
"name":"EUR",
"rate": 1,
"active": "no"
},{
"name": "PLN",
"rate": 4.1028,
"active": "no"
}, {
"name": "USD",
"rate": 1.1239,
"active": "no"
}
]
}
<div ng-repeat='cur in main.currencies'>
<label>{{cur.name}}</label>
<input type="number" min="0"
ng-model="cur.result"
ng-init='cur.result = ""'
ng-click='main.clear();'
ng-focus='main.active = cur; cur.active = true';
ng-blur='cur.active = false';
>
</div>
How could I input 1 value on active (focused) input and get calculated values on other inputs. I am very new to AngularJS and want to learn it with practical exercises.
Other values should follow such logic: cur.value = main.active.value / main.active.rate * cur.rate
.
But if I try instead of ng-model="cur.result"
:
ng-model="cur.result = main.active ? cur.result : cur.result/main.active.rate*cur.rate"
I can't write anything in input
Maybe I miss some ng*...
in input properties, but as far I know if I use ng-model
I should not use ng-name
and ng-value
...
Upvotes: 0
Views: 852
Reputation: 1716
try this JS:
angular.module('app',[]);
angular.module('app').controller('RateCtrl', RateCtrl);
function RateCtrl($scope){
var vm = $scope;
vm.cur = {};
vm.currencies = {/* your object */}
vm.setRate = function(model, rate){
return // your javascript
}
}
The HTML
<div ng-controller="RateCtrl as main">
<div ng-repeat="currency in main.currencies">
<label>{{currency.name}}</label>
<!-- Fyi, we are in an ng-repeat so there is an isolated scope. Sometimes '$parent.' must come before the objects outside ng-repeat -->
<input ng-model="main.cur.result" ng-focus="main.setRate(main.cur.result, currency.rate)">
</div>
</div>
This is one very basic way to manipulate the ng-model object. Alternatives include using Angular's filters, watchers, or decorators.
Upvotes: 1