AngularJS运行两次,而控制器只启动一次

时间:2015-10-17 13:59:04

标签: javascript angularjs

我一直在谷歌搜索一段时间,但似乎无法找到我的功能被执行两次的原因。我已经将代码愚蠢到几行,仍然无法弄明白。我在另一个应用程序上完全相同,但我不记得有同样的问题。也许你们可以帮助我。

angular.module('indexApp', []).controller('indexController', function ($scope) {
    console.log("init");
    $scope.somefunc = function (pEpochTime) {
        alert("Why does this execute twice?");
        return "asdf";
    };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular.min.js"></script>
<section ng-app="indexApp" ng-controller="indexController as indexCtrl">
    <div class="container">
        <div>{{somefunc('asdf')}}</div>
    </div>
</section>

http://jsfiddle.net/kcuqhf99/6/

1 个答案:

答案 0 :(得分:0)

当您使用函数绑定表达式而不是变量时,Angular将使用每个$ digest循环执行表达式。

添加了maurycy评论: 摘要运行两次,第一次由变量观察者运行,第二次检查第一次运行是否更改了另一个变量,因此您获得最少2次摘要运行,默认情况下最多10次

查看https://jsfiddle.net/1k2bg82v/1/

angular.module('indexApp', []).controller('indexController', function ($scope) {
    console.log("init");
    $scope.somefunc = function (pEpochTime) {
        alert("Why does this execute twice?");
        return "asdf";
    };

    $scope.do = function(){
        console.log('doing');
    };
});

我添加了与您的表达式无关的ng-click事件,但是当ng-click启动摘要循环时,它会再次触发您的函数。

在这里阅读更多关于$ watch的信息: https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope

  

如果您想在每次调用$ digest时收到通知,您可以   注册一个没有监听器的watchExpression函数。 (做好准备   多次调用watchExpression,因为它会执行   如果检测到更改,则在单个$摘要周期中多次。)