3

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.

Sam King
  • 90
  • 1
  • 5
  • possible duplicate of [AngularJS - Dynamically creating elements that specify directives](http://stackoverflow.com/questions/20025526/angularjs-dynamically-creating-elements-that-specify-directives) – Fals Dec 03 '14 at 15:16
  • It's not a duplicate of that question at all. – Sam King Dec 19 '14 at 09:30

1 Answers1

1

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>
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • It worked, thanks! There were a couple of minor changes that I had to make however: My templates needed a ng-bind-html="Content" to render the HTML properly and the src for the ng-include needed to become src="item.Type+'.html'" – Sam King Dec 04 '14 at 15:31