質問

Often when I get an error in Angular it causes an infinite loop in the browser and can lock down everything until I can kill the process. This tends to happen mostly when calling a function from a template with something like an ng-show.

<div ng-show="ifCanTakeAction()">
    <button ng-click="takeAction()></button>
</div>

If the function ifCanTakeAction gets an exception then it might become an infinite loop.

Obviously it is fairly easy to just fix the error in ifCanTakeAction but it is highly irritating that my computer goes for a short siesta every time it happens.

I am guessing the loop appears due to dirty-checking. Something in the crash of ifCanTakeAction causes another round of checks, which crashes it again, ad infinitum. Or it just dirty-checks that fires continuously. But how do you avoid this error? Is it simply ill-advised to run the function from the template like that? Often I would assign a model in the controller instead and look at that, but sometimes you have a case where the result might change as the user interacts with the page, which is why I base it on a function instead.

So, is this correct? Is it the dirty-checking that causes this issue? Would a watch do better (I assume that would get the same basic problem)? Is there a good way to catch and prevent infinite loops in general?

役に立ちましたか?

解決

ifCanTakeAction() should be replaced with a flag canTakeAction. Not only this will solve browser crashing, it will perform better. Currently angular is forced to call that function on every digest cycle. It makes much more sense to use a boolean value and to update it in controller when needed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top