Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    

1 Answer 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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.