在角的js控制方法无法获取模型值 [英] Cannot get model value in Controller method in Angular js

查看:126
本文介绍了在角的js控制方法无法获取模型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发展的角度JS应用程序

I am developing an app in Angular js

JavaScript的:

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)返回undefined。

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

但这种方法被调用
请咨询

But the method gets called Please Advice

推荐答案

究其原因,未定义是异步的行为。您code通过费用的收集将越快那么它被加载。检查 $腕表(watchEx pression,监听器,objectEquality)

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)

草案如何观察不断变化的colleciton 费用

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>

想想也引入类似$ scope.myModel = {费用:[],总:0} ...因为:

Also think about introducing something like $scope.myModel = { expenses : [], total : 0 }... Because:

如果您使用NG-模式必须有一个点的地方。如果你没有一个点,你这样做是错误的...

if you use ng-model there has to be a dot somewhere. If you don't have a dot, you're doing it wrong...

这篇关于在角的js控制方法无法获取模型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆