0

I have an anonymous function tied to the $scope in AngularJS. Problem is that the function is invoked 2 times and hence the "Hello!" is alerted twice.

I have no explicit watch defined on the function.

I know that this is somehow related to Angular digest cycle, but I am not able to understand how.

angular.module("root", [])
  .controller("index", function($scope) {
    $scope.myObj = {};
    $scope.myObj.text = function() {
      alert("Hello!");
      return "<b>Hello!</b>";
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js"></script>
<html>

  <body ng-app="root">
    <p ng-controller="index">
      <span ng-bind-html-unsafe="myObj.text()"></span>
    </p>
  </body>

</html>
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Anurag
  • 723
  • 3
  • 13
  • 31
  • 2
    See: https://stackoverflow.com/questions/19993294/angular-scope-function-executed-twice-when-it-should-only-run-once. Angular has to watch ng-bind-html-unsafe to update the DOM, and watched expressions are evaluated at least twice: the first time to update the value, the second time to ensure the value stays the same (checks possible side effects of the first first call) . – Yann May 09 '19 at 11:15

1 Answers1

0

One quick and maybe (dirty) way to fix this is:

angular.module("root", [])
  .controller("index", function($scope) {
    var initializeController = false;
    $scope.myObj = {};
    $scope.myObj.text = function() {
      if (!initializeController) {
        initializeController = true;
        alert("Hello!");
        return "<b>Hello!</b>";
      }
    }
  });