繁体   English   中英

在Angular JS中多次调用该函数

[英]Function called multiple times in Angular JS

考虑以下带有角度脚本的html文件:

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<head>
</head>
<body ng-app="TestFirstApp" ng-controller="TestCtrl">

<script>
var app = angular.module('TestFirstApp', []);
app.controller('TestCtrl', function($scope) {
    $scope.amt = 50000;
    $scope.terms = 1;
    $scope.rate= 10;
    $scope.interestamt= function() {
        console.log("New value of amt, terms and rate: "+$scope.amt+ " "+$scope.terms+" "+$scope.rate);
        return ($scope.amt*$scope.rate*$scope.terms)/100;   
    };                  
});
</script>
<div>
<label>Enter Amount</label><input type="number" ng-model="amt"></input>
<br>
<label>Enter Years</label><input type="number" ng-model="terms"></input>
<br>
<label>Enter Rate P.A.</label><input type="number" ng-model="rate"></input>
<br>
<label>The interest amount is : {{ interestamt() }}</label>

</div>
</body>
</html>

当我在浏览器中打开页面并更改输入框中的任何值时,由于绑定的原因,按预期计算了利息金额,并且标签标签中的值更新了。但是在控制台中,我注意到log语句被打印了3次每次我更改输入框中的三个值之一时,意味着该函数被多次调用。 谁能解释为什么多次调用该函数,而不是每次更改一次都调用一次?

这就是AngularJs的工作方式。 摘要过程在任何DOM事件上启动,以检查是否有任何作用域值已更改。

通常,在多次触发函数时将函数用于模板是一种不良的做法。 本文将帮助您了解:

https://medium.com/@piyalidas.gcetts/digest-cycle-in-angularjs-32cf6f6dcd5a

一种更干净的方法是在每个输入上使用ng-change ,并设置一个带有利息金额的变量:

<input type="number" ng-model="amt" ng-change="interestamt()" />

查看工作演示: DEMO

我不知道为什么多次被调用,但是我更改了代码并在视图的作用域值中声明了该名称,然后在控制器$scope.interestamt();调用了该函数$scope.interestamt(); ,它运行一次,我相信ng-init和您的函数将获得相同的结果,而不是返回来声明作用域中的值(interestamt)。

您也可以像这样在控制器中执行操作(请参阅jsfiddle2

$scope.ints = interestamt();;

其中interestamt()是:

    function interestamt() {
      console.log("New value of amt, terms and rate: "+$scope.amt+ " "+$scope.terms+" "+$scope.rate);
      return ($scope.amt*$scope.rate*$scope.terms)/100;   
    };

这是jsfiddle1的第一个示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM