PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

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

 May 18, 2022     angularjs, javascript, partial     No comments   

Issue

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.


Solution

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


Answered By - Trevor
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing