简体   繁体   中英

Retrieve values from dropdown in angularjs

I am not able to correctly apply the decimal rounding, which is selected by the user before calculating a total price, in this angular js app.

HTML

<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="lolCtrl">
  <form class = "col-md-6">
  <div class = "form-group">
    <label for = "prezzo"> Prezzo </label>
    <input type="number" class = "form-control" placeholder = "Prezzo" ng-model="price">
  </div>
  <div class = "form-group">
    <label for = "percentuale"> Percentuale </label>
    <input type="number" class = "form-control" placeholder = "Percentuale" ng-model="percent">
  </div>
  <div class = "form-group">
     <label for = "precisione"> n° decimali </label>
     <select class = "form-control" ng-model = "selectPrecision" ng-options="num.value as num.precision for num in decimali"></select>
  </div>
</form>
<button class = "btn btn-default" ng-click="percentuale()">Prezzo</button>
<p>Il risultato è:<span ng-model = "selectPrecision">{{risultato | number : 7}}</span></p>
  </div>
</body>

JS

var app = angular.module('myApp', []);

app.controller('lolCtrl', function($scope){
$scope.price = 20.232223;
$scope.percent = 20;

$scope.decimali= [
{value:0, precision: "0 decimali"},
{value:1, precision: "1 decimali"},
{value:2, precision: "2 decimali"}
];

$scope.percentuale = function (){
   $scope.risultato = $scope.price + $scope.price* $scope.percent/100;

}

});

I have fiddled a lot with this example because I don't want to create a custom filter but it lead me nowhere near the result I want:

Plunkr

I've put a fixed number of 7 decimals for the purpose of giving you working code. I would like it to be dynamic without custom filters because, well I just have to pass a parameter to an already existing framework filter function.

How it's done?

Just change your

<p>Il risultato è:<span ng-model = "selectPrecision">{{risultato | number : 7}}</span></p>

to

<p>Il risultato è:<span ng-model = "selectPrecision">{{risultato | number : selectPrecision}}</span></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM