4

I have an ng-repeat that acts like a switch condition that tells which template to render. I'm using ng-if inside the ng-repeat to achieve this. The problem? It's still evaluating the templates inside ng-if even if the condition evaluates to false which causes the entire thing to be slow.

<div ng-repeat="i in ...">
  <div ng-if="i == 'something1'">
    if this is false, do not evaluate this entire stuff
    .... some complex template goes here
  </div>
  <div ng-if="i == 'something2'">
    if this is false, do not evaluate this entire stuff
    .... another complex template goes here
  </div>
</div>

If the template inside each of the ng-if is complex and there are 20 ng-if inside ng-repeat and only one ng-if evaluates to true then 19 other templates will be wasting computing resources.

What can I possible do to mitigate this without resorting to programmatic approach and maintaining two-way binding for the template that is rendered?

supertonsky
  • 2,563
  • 6
  • 38
  • 68

1 Answers1

0

ng-if removes items from the HTML if the condition is false, so some rendering & evaluation may take place before that happens. If you nest ng-include inside of ng-if, the templates you load via ng-include are never evaluated.

Something like this:

<body ng-app="app">
    <div ng-controller="myController as ctrl">
        <div ng-if=true>
            Hi
            <div>{{ctrl.log(true)}}</div>
        </div>
        <div ng-if=false>
            Bye
            <ng-include src="foo.html"></ng-include>
            <div>{{ctrl.log(false)}}</div>
        </div>

    </div>
    <script>
        angular.module('app', []).controller("myController",myController);

        function  myController($scope){
            var ctrl = this;

            ctrl.log=function(val) {    
                console.log(val);
                return val;
            }
        };
    </script>
</body>
Mike Feltman
  • 5,160
  • 1
  • 17
  • 38