Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load HTML elements in AngularJS

Tags:

angularjs

I'm a complete beginner when it comes to AngularJS, having spent all of my time with jQuery in the past. What I'm trying to do is to read the content for a page from a data source, populate various HTML elements and then display them.

So what I have is this, content.json:

{
    "1" : {
        "Type" : "Title",
        "Content" : "Welcome to this Site"
    },
    "2" : {
        "Type" : "TextBox",
        "Content" : "<p>Introduction 1</p><p>Continued</p>"
    },
    "3" : {
       "Type" : "TextBox",
        "Content" : "<p>Do these tasks</p>"
    }
}

And then an HTML page that contains :

<div ng-app="myapp">
    <div ng-controller="content" id="Content">
        <!-- Dynamic content to be loaded here -->
    </div>
</div>

I have a couple of simple templates, TextBox.html :

<div class="TextBox">{{Content}}</div>

and Title.html :

<h1>{{Content}}</h1>

Finally my AngularJS code:

var app = angular.module('myapp', []);
app.controller('content', ['$scope','$http',function($scope,$http) {

    $http.get('content.json').success(function(data){
        $scope.elements = data;

        // What do I do now?
    });
}]);

Is it possible to iterate through the JSON data, load the template that is defined by the "Type" property, populate it using the "Content" property, and then display all the elements in the "#Content" div? How would I do that?

Is this the right approach to this sort of task in AngularJS? I get the feeling that I may be approaching this with a jQuery mindset and I wanted to check before I got too far.

like image 600
Sam King Avatar asked Feb 25 '26 13:02

Sam King


1 Answers

First use an array, not a dictionary:

[
    {
        "id": "1",
        "Type" : "Title.html",
        "Content" : "Welcome to this Site"
    },
    {
        "id" :"2",
        "Type" : "TextBox.html",
        "Content" : "<p>Introduction 1</p><p>Continued</p>"
    },
    {
       "id": "3",
       "Type" : "TextBox.html",
        "Content" : "<p>Do these tasks</p>"
    }
]

Second, use ng-init to alias Content, and ng-include to load the template. Repeat over your collection:

<div ng-app="myapp">
    <div ng-controller="content" id="Content">
        <!-- Dynamic content to be loaded here -->
        <div ng-repeat="item in elements" ng-init="Content=item.Content">
             <ng-include src="item.Type"></ng-include>
        </div>
    </div>
</div>
like image 103
pixelbits Avatar answered Feb 28 '26 08:02

pixelbits