我正在用 Angular js 开发一个应用程序
JavaScript:
$scope.spentAmount = function() {
angular.forEach($scope.expenses, function(expense) {
if(expense.done){
console.log($scope.spentamount);
}
});
//return amount;
};
HTML:
<label for="spentby">Spent by</label>
<ul class="unstyled">
<li ng-repeat="expense in expenses">
<input type="checkbox" ng-model="expense.done">
<span>{{expense.text}}</span>
<input type="text" ng-show="expense.done" ng-model="spentamount" size="30"
placeholder="Enter the amount">
</li>
</ul>
<form ng-submit="addExpense()">
<input type="text" ng-model="expenseText" size="30"
placeholder="Enter the names">
<input class="btn-primary" type="submit" value="Add">
</form>
<label for="amountspent">Amount spent(Rs)</label>
<span>{{spentAmount()}}</span><br>
但 console.log($scope.spentamount)
返回未定义。
但是该方法被调用 请指教
最佳答案
“未定义”的原因在于异步行为。您的代码在加载之前就会进行费用收集。检查$watch(watchExpression, listener, objectEquality)
如何观察不断变化的收集费用
的草案
// a new variable containing total
$scope.total = 0;
$scope.$watch('expenses', function (exps) {
angular.forEach(exps, function (exp) {
if(exp.done){
// here should/must be your calculation
$scope.total + exp.Amount;
}
});
});
现在我们可以调整模板并使用最新结果
<!--<span>{{spentAmount()}}</span><br>-->
<span>{{total}}</span><br>
还要考虑引入类似 $scope.myModel = { rates : [], Total : 0 }... 因为:
if you use ng-model there has to be a dot somewhere. If you don't have a dot, you're doing it wrong...
关于javascript - 无法在 Angular js 中的 Controller 方法中获取模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20851850/