AngularJS - 使用for循环生成数组

时间:2015-10-26 13:36:28

标签: javascript angularjs

我有一个非常简单的图片库,每个文件的顺序编号从001到235,并带有.jpg扩展名。

如何在不重复我的阵列235次的情况下循环001到235?

AngularJS代码:

(function(){
var app = angular.module('gallery', [ ]);

app.controller('controllerGallery', function(){
    this.images = photos;
});

var photos = [
    {
        thumb:  '001'
    },
    {
        thumb:  '002'
    },
    {
        thumb:  '003'
    },
];
})();

HTML code:

<html lang="en" ng-app="gallery">

<body ng-controller="controllerGallery as gallery">

<div class="container">
    <div class="thumb" ng-repeat="image in gallery.images">
        <a class="thumbnail" href="#"><img ng-src="/img/thumbs/{{image.thumb}}.jpg" /></a>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

自动创建数组:

var photos = [];
for (var i = 1; i <= 235; i++) {
    photos.push({ thumb: padLeft(i, 3) });
}

// utility function
function padLeft (num, length) {
    num = num.toString();
    while (num.length < length) {
        num = '0' + num;
    }
    return num;
}