使用ng-repeat重复具有不同id和ng-init的相同div

时间:2013-09-14 18:18:51

标签: angularjs angularjs-directive angularjs-ng-repeat ng-repeat

我如何使用ng-repeat重复这个结构的多个div(其中每个div的邻域不同,但其余部分是相同的)?

<div id="neighborhood" ng-controller="WeatherController" ng-init="init('neighborhood')">
  <h1>It's currently {{weather}}</h1>
  <p>Sunny: {{sunny}}</p>
  <p>Foggy: {{foggy}}</p>
  <input type="button" value="Sunny" ng-click="sunny = sunny + 1"/>
  <input type="button" value="Foggy" ng-click="foggy = foggy + 1"/>
</div>

1 个答案:

答案 0 :(得分:11)

您可以使用插值填充id并使用AngularJS的模型调用init

<div ng-app="myApp" ng-controller="WeatherController" >
    <div ng-repeat="item in data">
        <div id="{{item.id}}" ng-init="init(item.value)">
            ...
        </div>
    </div>
</div>

function WeatherController($scope) {
    $scope.init = function (item) {
        console.log(item);
    }

    $scope.data = [{
        id: 'neighborhood',
        value: 'neighborhood'
    }, {
        id: 'neighborhood1',
        value: 'neighborhood1'
    }]
}

DEMO