【问题标题】:Inline template of AngularJS does not work with XHTMLAngularJS 的内联模板不适用于 XHTML
【发布时间】:2016-12-24 07:09:05
【问题描述】:

我对带有 XHTML 的 AngularJS 内联模板的行为感到困惑。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="app">
<head>
<script type="text/ecmascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>

<script type="text/ecmascript">
    //<![CDATA[
    var app = angular.module('app', []);
    app.directive('dir',function(){ return{
        transclude: true,
        templateUrl: 'template'
        //template: '<div>Input: <span data-ng-transclude=""></span></div>'
        //if I use template instead of templateUrl, the code works well.
    }; });
    //]]>
</script>
<title>Angular JS template</title>
</head>

<body>
<script type="text/ng-template" id="template">
    <div>Input: <span data-ng-transclude=""></span></div>
</script>

<input type="text" data-ng-model="input"></input>

<div data-dir="dir"><span style="text-decoration: underline">{{input}}</span></div>

</body>
</html>

此代码适用于源 .html 的扩展,但使用 .xhtml&lt;div data-dir="dir"&gt; 的子节点变为空。

如果有人能告诉我更改扩展名会发生什么,我会很高兴。

【问题讨论】:

  • 嗯。你绝对需要它是多语言标记吗?使它在 XHTML 中工作的解决方案并不难,但它确实使它与 HTML 版本不兼容。
  • 谢谢。出于某些原因,希望我的源代码是机器可读的。因此,我正在尝试使用 XHTML。

标签: javascript angularjs xhtml angularjs-templates


【解决方案1】:

XHTML 对脚本的内容更加敏感。

解决方法:将模板中的&amp;lt;全部更改为&amp;lt;

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="app">
<head>
<script type="text/ecmascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>

<script type="text/ecmascript">
    //<![CDATA[
    var app = angular.module('app', []);
    app.directive('dir',function(){ return{
        transclude: true,
        templateUrl: 'template'
        //template: '<div>Input: <span data-ng-transclude=""></span></div>'
        //if I use template instead of templateUrl, the code works well.
    }; });
    //]]>
</script>
<title>Angular JS template</title>
</head>

<body>
<script type="text/ng-template" id="template">
    &lt;div>Input: &lt;span data-ng-transclude="">&lt;/span>&lt;/div>
</script>

<input type="text" data-ng-model="input"></input>

<div data-dir="dir"><span style="text-decoration: underline">{{input}}</span></div>

</body>
</html>

或者为模板使用 CDATA 块。

【讨论】:

  • 谢谢。它工作得很好。我无法想象&lt;script&gt; 的内容需要转义(因为它在我看来格式正确)!
  • 是的,这是 .xhtml 文件和 .html 文件之间的一个非常大的区别:在 HTML 中,
猜你喜欢
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 2016-12-24
  • 2013-04-14
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多