Cannot Get Model Value In Controller Method In Angular Js
I am developing an app in Angular js javascript: $scope.spentAmount = function() { angular.forEach($scope.expenses, function(expense) { if(expense.done){ console.
Solution 1:
The reason for the 'undefined' is in the async behaviour. Your code is going through the collection of expenses sooner then it is loaded. Check the $watch(watchExpression, listener, objectEquality)
a draft how to observe changing colleciton expenses
// 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;
}
});
});
now we can adjust the template and consume the up-to-date result
<!--<span>{{spentAmount()}}</span><br>--><span>{{total}}</span><br>
Also think about introducing something like $scope.myModel = { expenses : [], total : 0 }... Because:
if you use ng-model there has to be a dot somewhere. If you don't have a dot, you're doing it wrong...
Solution 2:
While binding inside the ng-repeat you need to use $parent to use parent scope, like-
<ling-repeat="expense in expenses"><inputtype="checkbox"ng-model="expense.done"><span>{{expense.text}}</span><inputtype="text"ng-show="expense.done"ng-model="$parent.spentamount"size="30"placeholder="Enter the amount" /></li>
Post a Comment for "Cannot Get Model Value In Controller Method In Angular Js"