2

I have following angular code

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

    <div ng-app="myApp" ng-controller="myCtrl">
        Test : {{mytest()}} 
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
            $scope.name= "John ";

            $scope.mytest = function () {
                console.log('my test');
                return 'something';
            };

        });
    </script>

</body>
</html>

For more detail, please refer to http://plnkr.co/edit/UIu50AOLMwKIJnAphIB5

Problem: when view in Chrome browser 'Inspect Element' console, the function 'my test' is called 3 times! Why ?

1 Answer 1

2

Because you've asked angular to do that. This expression

{{mytest()}} 

Is in fact instruction:

"angular, do check if the result value of mytest() is not changing. And do that regularly".

And angular is checking that few times, to be sure that it is not changed. And later, in some other digest it will do the same again

so, rather trigger that method once, and let angular to watch the resulting expression, like with a name above

{{name}}
Sign up to request clarification or add additional context in comments.

4 Comments

Really interesting!! Thanks Radim!
Any idea how to fix this problem ?
There are many ways. Really. Because it depends on your needs, on the effect which you want to reach. E.g. if you need to evaluate that only once, you can try this blog.thoughtram.io/angularjs/2014/10/14/… and syntax {{::myTest()}}
Great. I think that is the correct answer. Thanks Radim.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.