使用ngInclude包含多个部分

时间:2016-04-05 11:55:28

标签: html angularjs

我正在与WebApp进行angularJS我有一些令我恼火的事情。

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

每件物品,我都要写另一件物品。有没有办法在将来用一个命令包含这些和任何添加内容?

1 个答案:

答案 0 :(得分:1)

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

[编辑] 如果您想使用任何通用列表而不是原始帖子中的字母,请使用数组并使用任何内容对其进行初始化。

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

这里的要点是使用ng-repeat迭代您喜欢的任意数量的对象,并适当地动态创建ng-include元素。