AngularJS在django中开始加载部分,而不是在需要时加载

AngularJS load partials in the beginning and not at when needed in django?

本文关键字:加载 django 开始 加载部 AngularJS      更新时间:2023-09-26

我在django中有一个模板文件夹,我的应用程序的所有模板/部分都位于该文件夹中。我想在开始时将我的所有部分加载到angular的模板缓存中,而不是根据控制器的请求。

我有这样的路线设置:

var myApp = angular.module('myApp', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
    when('/landing', {
        templateUrl: '/landing-partial',
        controller: landingController
    }).
    when('/:wkspId/query', {
        templateUrl: '/query-partial',
        controller: queryController
    }).
    otherwise({
        redirectTo: '/landing'
    });
}]);

我想要类似于这个rails gem的解决方案(https://github.com/pitr/angular-rails-templates)在django。

根据您的构建系统,有一些插件可以为您解决这一问题。

对于GruntJS:https://www.npmjs.com/package/grunt-angular-templates

对于Gulp:https://www.npmjs.com/package/gulp-angular-templatecache

只要将它们指向你的html文件,它们就会创建一个javascript文件,看起来像:

  angular.module('app').run(["$templateCache", function($templateCache) {
  $templateCache.put("home.html",
    // contents for home.html ... 
  );

并将从那里解析模板,而不是发出http请求来获取实际文件。你只需要把这个js文件和你的应用程序脚本标签一起包含进去,你就可以开始了。

您可以在index.html中插入模板,如下所示:

<script type="text/ng-template" id="/landing-partial">
  Content of the template.
</script>
<script type="text/ng-template" id="/query-partial">
  Content of the template.
</script>

之后,您可以在路由器中使用这些模板:

var myApp = angular.module('myApp', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
    when('/landing', {
        templateUrl: '/landing-partial',
        controller: landingController
    }).
    when('/:wkspId/query', {
        templateUrl: '/query-partial',
        controller: queryController
    }).
    otherwise({
        redirectTo: '/landing'
    });
}]);

它的工作原理与您模块提供的类似。在angular引导之后,模板将被放入$templateCache,并且可以在任何地方使用。