I am me
I am me

Reputation: 131

Should a ngSubmit function call have a return statement in order to trigger the $digest cycle at the right time?

Say we have the following simple form:

<form ngSubmit="doSomething()">

    <input type="submit" value="Submit" />

<form>

And in the controller:

var ctrl = this;

ctrl.doSomething = function () {

    // Anything can happen here

}

I know the digest cycle is triggered by ngSubmit, but how does Angular know when to run the digest cycle? Is it run after doSomething() is complete, and if so how does angular know that doSomething() has indeed completed because I haven't seen any examples of ngSubmit functions using a return statement? e.g.

ctrl.doSomething = function () {

    // Anything can happen here

    // Add return statement so that angular knows callback is complete perhaps?
    return;

}

The reason I ask is because within my own doSomething() function I'm updating a scope value e.g. ctrl.myValue++. The updated value is being updated/reflected in the model fine but I don't understand how, or rather when, angular is able to ascertain that doSomething() has finished and it's now time to safely start the digest cycle.

Upvotes: 1

Views: 297

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

I know the digest cycle is triggered by ngSubmit

Yes, ngSubmit directive like ngClick triggers digest cycle

I haven't seen any examples of ngSubmit functions using a return statement?

Please read more about Scope Life Cycle

"... assignment such as $scope.username="angular" will not immediately cause a $watch to be notified, instead the $watch notification is delayed until the $digest phase. This delay is desirable, since it coalesces multiple model updates into one $watch notification as well as guarantees that during the $watch notification no other $watches are running. If a $watch changes the value of the model, it will force additional $digest cycle."

So when you call ctrl.myValue++, the model changes and it fires digest cycle

Add return statement so that angular knows callback is complete perhaps?

No, I don't think so and this approach has not mentioned in Angular DOCs

Upvotes: 0

Related Questions