javascript - 无法在 Angular js 中的 Controller 方法中获取模型值

标签 javascript angularjs

我正在用 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>

console.log($scope.spentamount) 返回未定义。

但是该方法被调用 请指教

最佳答案

“未定义”的原因在于异步行为。您的代码在加载之前就会进行费用收集。检查$watch(watchExpression, listener, objectEquality)

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

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

还要考虑引入类似 $scope.myModel = { rates : [], Total : 0 }... 因为:

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

关于javascript - 无法在 Angular js 中的 Controller 方法中获取模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20851850/

相关文章:

angularjs - 在 UI-Grid 标题中实现多列分组的任何更好的方法?

javascript - 如何使用选择列表从指令更新父级上的模型

javascript - 如何在 AngularJS 中使用 & 替换 &

javascript - 我可以在 Js 中更改对象的大小吗?

javascript - 为什么 Vue 单文件组件会编译成这么大的文件?

javascript - 为什么 getElementById() 无法识别表 id

javascript - 我将我的 div 设置为 bottom :0;, 并且 bottom 到底部,但是内容没有移动

javascript - 使用 RegEx 分解 html 源代码

angularjs - 带有 Angular 1 和 Bower 的 Webpack

angularjs - ui-router 填充 templateurl 和 Controller 嵌套抽象状态与嵌套 View