javascripthtmlangularjsangularjs-ng-include

AngularJS: many times use ng-include


I have old project. In this moment i can not rewrite all to use ng-view and routes. So i have large html file and many unreadable code.

<div ng-if="f1">
  <div>...</div>
</div>
<div ng-if="f2">
  <div>...</div>
</div>
<div ng-if="f3">
  <div>...</div>
</div> ....etc

I would like to break this code into blocks and use the ng-include to clean code. But then I will have a lot of this tag(> 10). Is it normal? Is there a way to reorganize the file differently?

<div ng-if="f1" ng-include="url1"> </div>
<div ng-if="f2" ng-include="url2"> </div>
<div ng-if="f3" ng-include="url2"> </div>

Solution

  • You should put your logic in an array in controller like this

    $scope.paths = [ 
            {url : "url1" , condition: $scope.f1},
            {url : "url2"  , condition: $scope.f2},
            {url : "url3" , condition: $scope.f3},
    ];
    

    And then use it in html like this

    <div ng-repeat="item in paths"> <div ng-if="item.condition" ng-include="item.url"></div> </div>