如何轻松地从角JS字符串呈现局部HTML? [英] How to easily render partial HTML from a string in angular js?

查看:191
本文介绍了如何轻松地从角JS字符串呈现局部HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这拨弄试图呈现字符串形式的两个谐音。当然,这个解决方案将无法正常工作(谐音呈现为 - 是,作为PTED角模板不跨$ P $)。

This fiddle tries to render two partials in string form. Of course, this solution won't work (the partials are rendered as-is and not interpreted as angular templates).

据我了解,我无论如何都必须使用 $编译服务,但我不太明白这一点。出于性能方面的原因,我想有每个部分只编译一次,然后只在本地更新。可 $编译做到这一点,如果是这样,怎么样?在我而言不会有太多的谐音,也没有多少改变集谐音,每个部分可以非常大(整个子页)。

From what I understand, I somehow have to use the $compile service, but I don't quite get it. For performance reasons, I would like to have each partial only compiled once and then only updated locally. Can $compile do that, and if so, how? In my case there are not many partials, not many changes to the set of partials and each partial can be very large (entire sub-page).

不,我不希望他们是在单独的文件。此外,意见都懒加载的。

And no, I do not want them to be in separate files. Also, the views are lazy-loaded.

时它甚至可以通过插入新模块来实现这个每个这样的部分

Is it maybe even possible to achieve this by inserting a new module for each such partial?

更新:

感谢 @threed ,我是能够解决这一切。 这是一个改进版本懒加载内容和控制器。

Thanks to @threed, I was able to fix it all up. This is an improved version with lazy-loaded content and controller.

推荐答案

您可以使用NG-include指令(见的这个的jsfiddle)...

You can use the ng-include directive (see this jsfiddle)...

HTML

<div ng-app="app" ng-controller="MyCtrl">
    <div ng-repeat="partial in partials">
        <div ng-include="partial.name"></div>
   </div>
</div>

JavaScript的:

JavaScript:

var app = angular.module('app', []);
var data = [
    'data1-apple',
    'data2-banana'
];
var partials = [
    {
        name: 'template1',
        content: '<div>{{data[0]}}</div>'
    },
    {
        name: 'template2',
        content: '<div>{{data[1]}}</div>'
    }
];
function MyCtrl($scope, $templateCache) {
    for(var i in partials){
        $templateCache.put(partials[i].name, partials[i].content);
    }
    $scope.partials = partials;
    $scope.data = data;
}

这篇关于如何轻松地从角JS字符串呈现局部HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆