How can directives be lazy loaded in angularjs?

后端 未结 4 1187
独厮守ぢ
独厮守ぢ 2020-12-30 01:58

I\'m working with angularjs and I want to be able to load directives as and when they are needed instead of having all of them loaded at the start of the page. I\'m trying

4条回答
  •  情书的邮戳
    2020-12-30 02:29

    If you want to register directives, after the application has been bootstrapped, you will have to use the $compileProvider instead of the module API. For example...

    $compileProvider.directive('SomeLazyDirective', function()
    {
        return {
            restrict: 'A',
            templateUrl: 'templates/some-lazy-directive.html'
        }
    })
    

    Then you can use the 'resolve' function when defining a route with the $routeProvider to load the lazy directive using your script loader. To do this, let the function return a promise that is resolved once your directive and other lazy dependencies have been loaded. AngularJS will wait for the promise to be resolved before rendering the route, thus ensuring that your directives will be ready before the view needs it. I have written a blog post detailing how to achieve lazy loading in AngularJS. It describes in more detail what I have stated here and it can be found at http://ify.io/lazy-loading-in-angularjs/

提交回复
热议问题