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>

1
  • 2
    See: stackoverflow.com/questions/19993294/…. 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) . Commented May 9, 2019 at 11:15

1 Answer 1

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>";
      }
    }
  });

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

Comments

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.