2

I am developing an app in 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>

but console.log($scope.spentamount) returns undefined.

But the method gets called Please Advice

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

Comments

0

While binding inside the ng-repeat you need to use $parent to use parent scope, like-

  <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>

1 Comment

Thanks I tried the above solution.When I tried to enter amount for various entries,the entry gets displayed in other text boxes of respective entries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.