使用Angularjs进行无服务器的Jade模板化

时间:2014-07-12 14:40:02

标签: javascript angularjs pug

我理解客户端模板呈现是一个有争议的主题,但在编写与所有Web服务器的兼容性时,它是必需的。

我在使用angularjs渲染玉石模板的简单解决方案后... 以下是一个过于简化的示例:http://jsfiddle.net/BqnR6/

angular.bootstrap(document)

该示例呈现单个页面并引导角度以评估元素。我之后的解决方案是使用路由来调用jade文件,渲染它们然后使用angularjs进行评估。

是否有办法或解决方法来实现此功能?

请注意,模板的渲染需要无服务器(即没有nodejs)。

1 个答案:

答案 0 :(得分:1)

以下是将所有模板嵌入角度ng-template脚本代码的解决方案:

<script type="text/ng-template" id="myTemplate.html" class="angular-template">
       <!-- jade template --></script>

对此的角度约定是type="text/ng-template"的ID是有效的模板URL,如果发现angular将从脚本标记中拉出,然后才会尝试通过ajax

在引导角度编译这些脚本标记的innerHtml之前

var templates = document.querySelectorAll('.angular-template')
for (i = 0; i < templates.length; i++) {
  templates[i].innerHTML = jade.compile(templates[i].innerHTML.trim())()
}

使用ng-view进行路由的应用示例:

var app = angular.module('plunker', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider.
  when('/', {
    templateUrl: 'myTemplate.html' /* note is same as script tag ID above*/
  });

});

app.controller('testApp', function($scope){
  $scope.title="See script tag for template";
   $scope.numbers = [1,2,3,4,5]
})

angular.bootstrap(document, ['plunker'])

DEMO