Ng-if: using plain expression instead of function call, does it make a difference?

I couldn’t find an answer so I’m bringing it up here.

Does it make a difference in resources or performance if I use

$scope.isAllowed = true;
<div ng-if="isAllowed"></div>

instead of

$scope.isAllowed = function() {
    return true;
};
<div ng-if="isAllowed()"></div>

I know Angular2+ has a advantange if i use the first option, but does this also apply to AngularJs?
For one time binding I could find {{::isAllowed}} at the expression guide but I don’t think that works in this case.

I also found out that the binding of ng-if makes it a watcher, what comes down to the $scope.$watch function. But that does not awnser the question.

Anyone has some more in-depth on this topic?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

No. Both results in creating one watcher. (I mean ofc something is a bit faster, but this is negligible.)

You can see difference when you care about code style and code maintainability.

E.g. When your page becoming slow, you wonder – whats up? And you open template:

<div ng-if="isAllowed"></div> this is just a watcher

<div ng-if="isAllowed()"></div> this is… you need to open controller file to see what it is

Now imagine you have 50 functions like this and some of them call another functions and they call functions from factories, etc. It might become really hard to understand what actually makes page slow.

So general rule for short expressions should be – no functions in ng-if, ng-show ng-bind, {{}} etc.
If u have smth like ng-if="conditionA && (conditionB || conditionC) || (conditionD && !conditionQ)" you may want to extract it into a function for readability and testing.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply