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.

2

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

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'"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.