1

I am making a WebApp with angularJS and I have something that irritates me.

<!doctype html>
<html>
<head>
<title>webapp</title>
<link href="css/angular-bootstrap.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="js/app.js"></script>
</head>

<body ng-app="app">

<div class="container">
    <h1>WebApp</h1>
    <div ng-controller="home as homeCtrl" ng-cloak class="ng-cloak" class="wrapper">
        <div ng-include="'blocks/item.html'"></div>
        <div ng-include="'blocks/something.html'"></div>
        <div ng-include="'blocks/health.html'"></div>
        <div ng-include="'blocks/mana.html'"></div>
        <div ng-include="'blocks/running.html'"></div>
        <div ng-include="'blocks/out.html'"></div>
        <div ng-include="'blocks/of.html'"></div>
        <div ng-include="'blocks/ideas.html'"></div>
    </div>
</div>
</body>

</html>

Every item, i have to write another include. is there a way to include these and any additions in the future with one command?

ziraak
  • 131
  • 3
  • 14

1 Answers1

1

Firstly, in your controller create the alphabet array (as shown here)

function genCharArray(charA, charZ) {
    var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
    for (; i <= j; ++i) {
        a.push(String.fromCharCode(i));
    }
    return a;
}
$scope.charArray = genCharArray('a', 'z'); // ["a", ..., "z"]

Then, in your template:

<div ng-controller="home as homeCtrl" ng-cloak class="ng-cloak" class="wrapper">
    <div ng-repeat="letter in charArray" ng-include="'blocks/' + letter + '.html'"></div>
</div>

[edit] If you want to work with any generic list and not specifically the alphabet as in the original post, just use an array and initialize it with whatever.

$scope.charArray = ['lemon', 'tree', 'apple'];

The point here is using ng-repeat to iterate over any number of objects you like, and dynamically create the ng-include elements appropriately.

Community
  • 1
  • 1
AlexD
  • 4,062
  • 5
  • 38
  • 65
  • sorry. i used the alfabet as placeholder for the filenames. This may work in that case but not the one i have. – ziraak Apr 05 '16 at 12:39
  • Edited my answer, but just initialize the array with anything you like. – AlexD Apr 05 '16 at 12:44