0

Just wondering if there is a recommended solution for the following scenario.

I have a complex expression in my markup to show some error message, e.g.

ng-show="currentSection == 'pickup-from' && carHireEnquiryForm.pickUpLocation.$dirty && carHireEnquiryForm.pickUpLocation.$invalid && carHireEnquiryForm.pickUpLocation.$error.isLocation"

This can make the markup messy and hard to unit test, so to get around this I created a function for this, e.g.

ng-show="isShowError()"

Now the isShowError can easily be tested. Problem now is that the isShowError is invoked on every digest even if the element is not visible. This for me is even worst as performance it very important.

Is there a better way to achieve this? Is expressions the recommend way to do this? What if the expression had to include 20 statements? I am keen to reduce the amount of business logic in my markup as well.

Thanks in advance

Cuong
  • 127
  • 11

1 Answers1

3

There is not much of a difference between using function and expression, considering the fact that the function is also evaluated like an expression.

Implies if you are just using an expression, that too is being evaluated on every digest cycle. The function just add lightweight indirection.

As long as the expression evaluation is fast you can use either, but functions are better as they can encapsulate the validation logic.

The problem comes when we knowingly or unknowingly add some time consuming operation to the function, slowing down the function evaluation.

Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • Does the expression get evaluation on every digest or does it use a watch that only gets evaluated when it 'changes'? I wasn't sure how to prove this. – Cuong Feb 10 '15 at 13:02
  • To be honest that was exactly my thinking to begin with....."so what the functions runs a extra few times".....but 6 months done the line following the same patterns I now have 000s of unnecessary 'small' function calls and I think this is killing my app on mobile devices. – Cuong Feb 10 '15 at 13:06
  • To determine `when it changes` it has to be evaluated on every digest cycle. See also http://stackoverflow.com/questions/9682092/databinding-in-angularjs – Chandermani Feb 10 '15 at 13:07
  • @Cuong, what Angular does it take the expression, and evaluate it every time digest cycle occurs. It does not care if it is a function or bunch of statements. It caches the return value from the evaluation for future comparison. – Chandermani Feb 10 '15 at 13:09
  • Thats a lot for that, very interesting and potentially saved me a lot of effort. – Cuong Feb 10 '15 at 13:26