gpt4 book ai didi

javascript - Angular - 检查数据是否存在?

转载 作者:行者123 更新时间:2023-11-28 01:51:18 26 4
gpt4 key购买 nike

我正在创建一个小型计算器,它通过绑定(bind)创建多个值。有一个更好的方法吗?我觉得这完全是黑客行为。我是 Angular 新手。

计算器:

<div ng-app="App" ng-controller="CalculatorCtrl">
<form action="javascript:;" id="calculator" class="form-inline">
<fieldset class="grid grid-4">
<div class="item">
<input required type="number"
ng-model="data.buy"
placeholder="Buy Price"
maxlength="10"
tabindex="1" />
</div>

<div class="item">
<input required type="number"
ng-model="data.sell"
placeholder="Sell Price/target"
maxlength="10"
tabindex="2" />
</div>

<div class="item">
<input required type="number"
ng-model="data.shares"
placeholder="Share Count"
maxlength="10"
tabindex="3" />
</div>

<div class="item">
<input required type="number"
ng-model="data.fee"
placeholder="Commission Fee"
maxlength="10"
tabindex="3" />
</div>
</fieldset>
</form>

<!-- Results -->
<table class="table table-bordered table-striped table-hover">
<tr>
<th width="150">Total Profit</th>
<td>{{ profit() | number:2 }}%</td>
</tr>

<tr>
<th width="150">Net Gain</th>
<td>{{ data.net = (data.soldFor - data.purchasedFor) | currency }}</td>
</tr>

<tr>
<th width="150">Purchased For</th>
<td>{{ data.purchasedFor = (data.buy * data.shares) + data.fee | currency }}</td>
</tr>

<tr>
<th width="150">Sold For</th>
<td>{{ data.soldFor = (data.sell * data.shares) - data.fee | currency }}</td>
</tr>
</table>
</div>

有问题的 JS(coffeescript):

# Core Coffee
app = angular.module 'App', []
app.controller 'CalculatorCtrl', ['$scope', ($scope) ->
$scope.profit = ->
data = $scope.data
return 0 unless data? and data.net? and data.purchasedFor? and data.soldFor?

a = if data.soldFor > data.purchasedFor then data.soldFor else data.purchasedFor
b = if a is data.soldFor then data.purchasedFor else data.soldFor

res = if data.net >= 1 then '+' else '-'
res += ((a - b) / b) * 100
]

如果没有这一行,我如何确保数据存在(就像 Angular 自动执行的那样)? 返回 0 除非有数据?和数据网?和 data.purchasedFor?和 data.soldFor?

编辑:感谢 Maxim,这工作得很好:

### Watch for the net gain value and then calculate a profit % ###
$scope.$watch 'data.net', (newVal, oldVal) ->
return 0 unless newVal?
data = $scope.data

a = if data.soldFor > data.purchasedFor then data.soldFor else data.purchasedFor
b = if a is data.soldFor then data.purchasedFor else data.soldFor

$scope.data.profit = if newVal >= 1 then '+' else '-'
$scope.data.profit += ((a - b) / b) * 100

最佳答案

我会使用$watch来监听数据

查看文档 here

通常,带有标志 true$watch 会进行深度比较。

类似于(希望你能将其转换为咖啡):

$scope.$watch(function () {
return$scope.data;
},
function (newValue, oldValue) {
// here you can write any action
}, true);

关于javascript - Angular - 检查数据是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19666971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com