spiderman spiderman - 14 days ago 8
AngularJS Question

How to perform calculation on AngularJS with Percentage value

Can you help me in doing calculation on AngularJS during data binding?
There is one more issue here, as the discount value is not numeric. It's a string with '%' appended.

My current output:

Actual: 1000
Discount: 10%
Price after discount : 10% [I want the calculation here. 1000-(.1*1000) ie 900]

Actual: 600
Discount: 5%
Price after discount : 5% [I want the calculation here]


index.html

<body ng-app="myApp">
<div ng-controller="ItemCtrl">
<span ng-repeat="item in items">
<div>Actual: {{item.actual}}</div>
<div>Discount: {{item.discount}}</div>
<div>Price after discount : {{item.discount}}</div>
<hr>
</span>
</div>


app.js

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

myApp.controller('ItemCtrl', ['$scope', function($scope) {
$scope.items = [{
"discount": "10%",
"actual": "1000"
}, {
"discount": "5%",
"actual": "600"
}];
}]);


Here's my jsfiddle link : http://jsfiddle.net/960bhxab/1/

Answer

It's better to keep the logic out of the dom.

http://jsfiddle.net/errvald/960bhxab/4/

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

myApp.controller('ItemCtrl', ['$scope', function($scope) {
  $scope.items = [{
    "discount": "10%",
    "actual": "1000"
  }, {
    "discount": "5%",
    "actual": "600"
  }];
  
  $scope.items.forEach(function(item){
    item['price'] = item.actual - (item.actual*item.discount.slice(0, -1))/100;
  });
  
}]);
.rating {
  color: #a9a9a9;
  margin: 0;
  padding: 0;
}

ul.rating {
  display: inline-block;
}

.rating li {
  list-style-type: none;
  display: inline-block;
  padding: 1px;
  text-align: center;
  font-weight: bold;
  cursor: pointer;
}

.rating .filled {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="ItemCtrl">
    <span ng-repeat="item in items">
    <div>Actual: {{item.actual}}</div> 
      <div>Discount: {{item.discount}}</div> 
       <div>Price after discount : {{item.price}}</div> 
       <hr>  
        </span>
  </div>
</body>