Angularjs:如何重复未知数量的div?

时间:2016-01-25 17:54:50

标签: javascript html angularjs

我想构建与div变量一样多的$scope.fileContent,如下所示:

<div class="dd-nodrag" ng-nestable ng-model="fileContent">
    <div>
        {{$item.title}} {{$item.value}}
    </div>
</div>

<div class="dd-nodrag" ng-nestable ng-model="fileContent1">
    <div>
        {{$item.title}} {{$item.value}}
    </div>
</div>

<div class="dd-nodrag" ng-nestable ng-model="fileContent2">
    <div>
        {{$item.title}} {{$item.value}}
    </div>
</div> 


          ...

<div class="dd-nodrag" ng-nestable ng-model="fileContentN">
    <div>
        {{$item.title}} {{$item.value}}
    </div>
</div> 

有没有办法只写这样的东西:

<div class="dd-nodrag" ng-nestable ng-model="fileContent">
    <div>
        {{$item.title}} {{$item.value}}
    </div>
</div> 

并像我$scope.fileContent

那样多次重复此操作

这没有任何意义,但我想做的是:

for(i = 0 ; i < N ; i++) {
    <div class="dd-nodrag" ng-nestable ng-model="fileContent"+i>
        <div>
            {{$item.title}} {{$item.value}}
        </div>
    </div> 
}

2 个答案:

答案 0 :(得分:2)

是的,只需使用ng-repeat:

<div class="dd-nodrag" ng-repeat="fileContent in fileContents">
    <div>
        {{fileContent.title}} {{fileContent.value}}
    </div>
</div>

您可以在此处详细了解:

https://docs.angularjs.org/api/ng/directive/ngRepeat

答案 1 :(得分:0)

根据您的代码,似乎您在$ scope中有自变量(对象),如:

    $scope.fileContent = {}
    $scope.fileContent1 = {}
    $scope.fileContent2 = {}
    $scope.fileContent3 = {}
    .
    $scope.fileContentN = {}

如果是,您可能希望将自变量(对象)封装在javascript数组(JSON)中,如:

    $scope.fileContents = [{ title: "T0", value: "V0" }, 
                           { title: "T1", value: "V1" }, 
                           { title: "T2", value: "V2" }];

您可以使用angularjs中的ng-repeat循环遍历javascript数组,如jeremy建议的那样:

    <div class="dd-nodrag" ng-repeat="fileContent in fileContents">
        <div>
            {{fileContent.title}} {{fileContent.value}}
        </div>
    </div>