你能帮我在数据绑定期间对AngularJS进行计算吗? 这里还有一个问题,因为折扣价值不是数字。它是一个带有'%'的字符串。追加。
我目前的输出:
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"
}];
}]);
这是我的jsfiddle链接:http://jsfiddle.net/960bhxab/1/
答案 0 :(得分:1)
如果您可以从数据中删除%符号,它会使数学运算更容易吗?
<div>Price after discount : {{item.actual - item.actual/100*item.discount}}</div>
答案 1 :(得分:1)
这很简单。将%移出变量,因此它只是用于显示,然后计算很简单:
<div>Discount: {{item.discount}}%</div>
<div>Price after discount : {{item.actual*(100-item.discount)/100}}
答案 2 :(得分:1)
将逻辑排除在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;
});
}]);
&#13;
.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;
}
&#13;
<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>
&#13;
答案 3 :(得分:0)
我发现自己
继承人JSFiddle。如果有更好的方法,请告诉我。
http://jsfiddle.net/960bhxab/2/
<强> 的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.actual-(item.actual*item.discount.replace('%', '')/100)}}</div>
<hr>
</span>
</div>
</body>