我想循环一个包含 X 个项目的 JSON 对象,然后显示这些项目 - 但是,它必须输出不同的 html,具体取决于它在循环中的位置。例如:Article1 的布局与 Article2-3-4 的布局不同 - Article5-6-7 的布局与其余布局不同,我将如何使用 Angular 执行此操作,是否可以使用指令或我是否需要其他东西?如果是这样,我该怎么做?到目前为止我已经知道了:
DIS.dbuApp.controller('newsController', ['$scope', '$http', function($scope, $http) {
//URL for retrieving JSON object
$scope.url = 'http://jsonplaceholder.typicode.com/posts';
$scope.items = [];
$scope.fetchContent = function() {
$http.get($scope.url)
.success(function(data, status){
if(typeof(data === "object") && data.length > 0) {
console.log("test");
//We got the data, and it is and object
$scope.items = data;
//Now set variable to tru
$scope.showresult = true;
//If first item use this directive:
_.each($scope.items, function(value, index){
//console.log(index);
if(index === 0) {
//When position 0, render a directive with some specific html
console.log(index);
} else if(index > 0 && index < 5) {
//When position greater than 0 and lower than 5, render another directive with some specific html
console.log(index);
} else if(index > 4 && index < 9) {
//Same as above, but with different html
console.log(index);
} else if(index > 8 && index < 12) {
//Same as above, but with different html
console.log(index);
}
_.each(value, function(value, key){
//console.log(value + key); // 0: foo, 1: bar, 2: baz
});
});
//If second to fifth item, use this directive
//If six to 10, use this directive
}
})
.error(function() {
console.log("There was an error, contact the developer, or check your internet connection" + status);
});
};
$scope.fetchContent();
}]);
最佳答案
如果数据类型的数量有限,例如 3-5,并且您需要它们之间非常不同的功能 - 而不仅仅是不同的布局,则可以为每种数据类型使用一个指令。在这种情况下,您可以使用 ng-switch:
<div ng-switch="$index">
<div ng-switch-when="1" number1directive />
或者,您可以有一个指令,并在链接函数中确定要呈现的模板,将索引作为独立范围传递给它。
<div ng-repeat="item in items">
<div mydirective item-index="$index" item-data="item" />
</div>
如果最后一个选项在功能上非常相似,但具有不同的模板,那么它们将更加简洁和可扩展。
更新:
内部使用 nginclude
的指令示例。
app.directive("dynamicTemplate", function () {
return {
template: '<ng-include src="getTemplateUrl()" />',
scope: {
index: '@',
item: '='
},
restrict: 'E',
controller: function ($scope) {
// function used on the ng-include to resolve the template
$scope.getTemplateUrl = function () {
if ($scope.index === 0) {
return "template0.html";
} else if ($scope.index > 0 && $scope.index < 5) {
return "template1-4.html";
} else if ($scope.index > 4 && $scope.index < 9) {
return "template5-8.html";
} else if ($scope.index > 8 && $scope.index < 12) {
return "template9-11.html";
}
}
}
}
});
在 HTML
中实现为:
<dynamic-template index="$index" item="item"><dynamic-template>
无论如何,这就是想法。希望您能够使用这种方法,也许需要进行一些小的改进。
关于javascript - 循环对象,根据位置输出不同的html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33730557/