ng-repeat with ng-include not working

前端 未结 3 820
梦毁少年i
梦毁少年i 2021-02-14 19:07

I am trying to use an ng-repeat that includes an ng-include. The problem is that the first element in the ng-repeat is just the ng-include

相关标签:
3条回答
  • 2021-02-14 19:20

    Using a directive worked for me: https://stackoverflow.com/a/24673257/188926

    In your case:

    1) define a directive:

    angular.module('myApp')
      .directive('mytemplate', function() {
        return {
          templateUrl: 'views/template.html'
        };
      });
    

    2) use your new directive:

    <mytemplate />
    

    ... or if you're concerned about HTML validation:

    <div mytemplate></div>
    
    0 讨论(0)
  • 2021-02-14 19:22

    First make sure that the data that is contained in the first index of items actually has the data that you want.

    One possible solution to your problem would be to simply not show the first index of the ng-repeat:

    <div ng-repeat="item in items" ng-show="!$first">
       <div ng-include src="'views/template.html'"></div>
    </div>
    

    This may not actually tackle the root of your problem, but it may still get your application working a bit more like what you expect.


    Another possible solution:

    <div ng-repeat="item in items" ng-include="'views/template.html'"></div>
    

    see example here:

    http://plnkr.co/edit/Yvd73HiFS8dXvpvpEeFu?p=preview


    One more possible fix just for good measure:

    Use a component:

    html:

    <div ng-repeat="item in items">
       <my-include></my-include>
    </div>
    

    js:

    angular.module("app").directive("myInclude", function() {
    return {
        restrict: "E",
        templateUrl: "/views/template.html"
    }
    })
    
    0 讨论(0)
  • 2021-02-14 19:29

    I ran into the same problem, and finally figured out that the first element has not been fetched and compiled in time for the first ng-repeat iteration. Using $templateCache will fix the problem.


    You can cache your template in a script tag:

    <script type="text/ng-template" id="templateId.html">
        <p>This is the content of the template</p>
    </script>
    


    Or in your app's run function:

    angular.module("app").run(function($http, $templateCache) {
        $http.get("/views/template.html", { cache: $templateCache });
    });
    


    You can also use $templateCache inside your directive, although it's a bit harder to setup. If your templates are dynamic, I would recommend creating a template cache service. This SO question has some good examples of template caching inside a directive and a service:

    Using $http and $templateCache from within a directive doesn't return results

    0 讨论(0)
提交回复
热议问题