简体   繁体   中英

How to easily render partial HTML from a string in angular js?

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?

UPDATE:

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

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:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM