Alan2
Alan2

Reputation: 24572

How often does my HTML call a function?

I have this code in my HTML:

 <div >{{ getHint(us.q.hint) }}</div>

Can someone tell me when the function will be called? Is it called many times or just the once when us.q.hint changes value?

Update

I have a few answers and they're different. Is there a way that I could make the function call only each time the value changes?

Upvotes: 0

Views: 58

Answers (3)

Jack A.
Jack A.

Reputation: 4453

Many times.

Interpolations (the {{ ... }} construct) are evaluated during every iteration of the digest cycle. The digest cycle happens for every event that is handled by Angular, and there can be multiple iterations per digest cycle.

An interpolation creates a watcher on the interpolated expression. The digest cycle loops through all watchers and evaluates each one to detect changes that need to be applied to the view. The digest code detects changes by evaluating each expression and comparing it to the previous value. This means that every watched expression is evaluated/executed at least once during every digest cycle.

In your case, the interpolated expression is getHint(us.q.hint). When that expression is evaluated, the $scope.getHint function is called and passed in the value of $scope.us.q.hint. The return value from getHint is compared to the previous value to determine if it has changed.

So you see, it is not the value of $scope.us.q.hint that is being watched, it is the value of the entire expression.

See more info on interpolations, watches, and the digest cycle.

Update for Update

If you want your function to get called only when the argument changes, you could do it with two changes:

  1. Create a watch on the value that will change and call getHint in the watcher.
  2. Create a scope variable to hold the result of the getHint call and bind that to the view.

So in your controller (every watcher gets called at least once, which will initialize $scope.hint):

$scope.$watch('us.q.hint', function () {
    $scope.hint = $scope.getHint($scope.us.q.hint);
});

And in your view:

<div >{{ hint }}</div>

Upvotes: 3

Ruwantha R.
Ruwantha R.

Reputation: 82

yes each time us.q.hint value change it will be executed as it is being watched.

Upvotes: -1

Hassan Tariq
Hassan Tariq

Reputation: 740

This will be called more than one time infact as many time as your html render or page is refreshed this will not be dependent on change in value of

 us.q.hint

Upvotes: 0

Related Questions