<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.5.0-rc.0" data-semver="1.5.0-rc.0" src="https://code.angularjs.org/1.5.0-rc.0/angular.js"></script>
<script data-require="jquery@*" data-semver="2.1.4" src="https://code.jquery.com/jquery-2.1.4.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<page></page>
</body>
</html>
angular.module('app', [])
.factory('dataService', function() {
return {
getdata: function() {
return [{
id: 1,
type: "my-component",
text: "This is data service text",
data: "Component data here",
components: [{
id: 4,
type: "component2",
text: "This is test",
data: "More Component data here"
}, {
id: 5,
type: "component2",
text: "This is test",
data: "More Component data here"
}]
}, {
id: 2,
type: "component2",
text: "This is test",
data: "More Component data here"
}, {
id: 3,
type: "final-component",
text: "final text",
data: "Final Component data here"
}]
}
}
})
// Main Component
.component('page', {
template: function($element, $attrs) {
//console.log($element);
//console.log($attrs);
return ["<h1>page template</h1>",
//"<pre>{{ ctrl.data | json }}</pre>",
//"<my-component test='this is attribute text'></my-component>"
].join("");
},
controller: pageController,
controllerAs: 'ctrl'
});
// Main component controller
pageController.$inject = ['$scope', 'dataService', '$compile'];
function pageController($scope, dataService, $compile) {
this.data = dataService.getdata()
// loop through the data and inject components
for (var i = 0; i < this.data.length; i++) {
var newScope = $scope.$new(true, $scope);
newScope = angular.merge(newScope, this.data[i]);
var html = '<' + this.data[i].type + ' test="' + this.data[i].text + '"></' + this.data[i].type + '>';
var element = $('page');
element.append($compile(html)(newScope));
console.log(newScope);
}
}
// 3 Child compoenents to dynamically load
angular.module('app')
.component('myComponent', {
controller: function() {},
bindings: {
data: '='
},
template: function($element, $attrs) {
return "<h3>Component 1</h3><p>" +
$attrs.test +
"</p><p>{{ data }}</p>";
}
})
.component('component2', {
bindings: {
data: '='
},
template: function($element, $attrs) {
return "<h3>Component 2</h3><p>" +
$attrs.test +
"</p><p>{{ data }}</p>";
}
})
.component('finalComponent', {
bindings: {
data: '='
},
template: function($element, $attrs) {
return "<h3>Component 3</h3><p>" +
$attrs.test +
"</p><p>{{ data }}</p>";
}
});
<h3>Component 1</h3><p>" +
$attrs.test +
"</p><p>{{ data }}</p>