使用 ngInclude 包含多个部分

include multiple parts using ngInclude

我正在用 angularJS 做一个 WebApp,我有一些事情让我很恼火。

<!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>

每个项目,我都必须写另一个包含。有没有一种方法可以通过一个命令包含这些以及将来的任何添加?

首先,在您的控制器中创建字母数组 (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"]

然后,在您的模板中:

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

[编辑] 如果你想使用任何通用列表,而不是像原始 post 中那样具体的字母表,只需使用一个数组并用任何东西初始化它。

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

这里的重点是使用 ng-repeat 遍历任意数量的对象,并适当地动态创建 ng-include 元素。