Javascript 无法在Angular js中的控制器方法中获取模型值
我正在用AngularJS开发一个应用程序 javascript:Javascript 无法在Angular js中的控制器方法中获取模型值,javascript,angularjs,Javascript,Angularjs,我正在用AngularJS开发一个应用程序 javascript: $scope.spentAmount = function() { angular.forEach($scope.expenses, function(expense) { if(expense.done){ console.log($scope.spentamount); } }); //return amount; }; HTML: {
$scope.spentAmount = function() {
angular.forEach($scope.expenses, function(expense) {
if(expense.done){
console.log($scope.spentamount);
}
});
//return amount;
};
HTML:
-
{{expense.text}
支出金额(卢比)
{{spentAmount()}}
但是console.log($scope.spentamount)
返回未定义的
但是这个方法被调用了
请注意,在ng内部绑定时,您需要使用$parent来使用父作用域,如-
<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="$parent.spentamount" size="30"
placeholder="Enter the amount" />
</li>
{{expense.text}
导致“未定义”的原因在于异步行为。在加载代码之前,您的代码正在进行费用收集。检查
如何观察不断变化的学院费用草案
// 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>
{{total}}
还可以考虑引入类似$scope.myModel={expenses:[],total:0}之类的内容。。。因为:
如果你使用ng模型,就必须在某处有一个点。如果你没有圆点,你就做错了
谢谢,我尝试了上述解决方案。当我尝试为各种条目输入金额时,条目会显示在相应条目的其他文本框中
<!--<span>{{spentAmount()}}</span><br>-->
<span>{{total}}</span><br>