来自url的角度加载模板并在div中编译

Rol*_*and 18 javascript angularjs

由于我是Angular JS的新手,我想知道如何加载外部模板并将其与一些数据一起编译到目标模板中div.

例如,我有这个模板:

<script type="text/ng-template">

    <img src="{{Thumb}}" />

<script>
Run Code Online (Sandbox Code Playgroud)

div所应该包含的模板:

<div data-ng-controller=" ... "></div>
Run Code Online (Sandbox Code Playgroud)

模板位于文件夹中的某个位置/templates/test.php.是否有像构建指令那样进行模板加载的构建方法,并针对某些替换密钥的数据{{Thumb}}(当然还有很多其他数据)进行编译?

编辑:如果我$routes在网站的根目录中使用并加载模板怎么办?怎么可能实现?

cda*_*uth 26

使用$templateRequest,您可以通过它的URL加载模板,而无需将其嵌入到HTML页面中.如果模板已加载,则将从缓存中获取.

app.controller('testCtrl', function($scope, $templateRequest, $sce, $compile){
    // Make sure that no bad URLs are fetched. If you have a static string like in this
    // example, you might as well omit the $sce call.
    var templateUrl = $sce.getTrustedResourceUrl('nameOfTemplate.html');

    $templateRequest(templateUrl).then(function(template) {
        // template is the HTML template as a string

        // Let's put it into an HTML element and parse any directives and expressions
        // in the code. (Note: This is just an example, modifying the DOM from within
        // a controller is considered bad style.)
        $compile($("#my-element").html(template).contents())($scope);
    }, function() {
        // An error has occurred here
    });
});
Run Code Online (Sandbox Code Playgroud)

请注意,这是手动方式,而在大多数情况下,最好的方法是定义使用属性获取模板的指令templateUrl.


Yah*_*CEM 18

在Angular中有两种使用模板的方式(我至少知道两种方式):

所以你需要做的是从模板中删除脚本部分,然后在想要的div中使用ng-include,如下所示:

<div ng-include="'templates/test.php'"></div>

需要双引号和单引号才能工作.希望这可以帮助.

  • 对于图像,你应该使用ngSrc:`<img rel="nofollow noreferrer" ng-src ='Thumb'>` (2认同)