无法在控制器中访问Angular js-model中的$ watch

时间:2013-12-31 08:53:50

标签: javascript angularjs

我尝试使用$ watch来获取

中输入的数据
<input type="text"  ng-show="expense.done" ng-model="spentamount"  size="30"
                 placeholder="Enter the amount">

的javascript:

  $scope.spentAmount = function() {    
angular.forEach($scope.expenses, function(expense) {
 if(expense.done){
 $scope.$watch('spentamount',function () {      
  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"><span>{{addExpenseAmount()}}</span>      
             </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><br>         
<label for="amountspent">Amount spent(Rs)</label>
 <span>{{spentAmount()}}</span><br>

但是console.log($scope.spentamount)说&#39; undefined&#39;

我对$ watch的使用是否正确?

请咨询

1 个答案:

答案 0 :(得分:1)

您的控制器无法监视“spentamount”变量,因为它未在控制器范围内定义,而是在ng-repeat迭代范围内定义。

请参阅:

<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"><span>{{addExpenseAmount()}}</span>      
</li>

这意味着当您在输入中键入内容时,在内部范围内更新了spendamount:

$scope of your controller
  -> First ng-repeat iteration create a new scope
    -> New 'expense' and 'spentamout' variables are defined here
  -> Second ng-repeat iteration create a new scope
    -> New 'expense' and 'spentamout' are defined here

您可以做的是在更新了spendamout时应用更改事件:

<li ng-repeat="expense in expenses">
    <input type="checkbox" ng-model="expense.done">
    <span>{{expense.text}}</span>
    <input type="text" size="30" placeholder="Enter the amount"
           ng-show="expense.done"
           ng-model="spentamount"
           ng-change="onAmountUpdated(spentamount, expense)">
    <span>{{addExpenseAmount()}}</span>      
</li>

在您的控制器中:

$scope.onAmountUpdated = function(spentamount, expense) {
    console.log(spentamount, expense);
};

看到这个小提琴:http://jsfiddle.net/Pa633