Search code examples
javascriptangularjsangularjs-ng-if

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?


Solution

  • 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.