When using a ng-repeat, how should I use a controller inside it?
For example, if I'm looping over a set of days in a week:
<ul ng-controller="WeekCtrl">
<li ng-repeat="d in days">
<span ng-controller="DayCtrl">
{{dayOfWeek}} {{date}}: {{info}}
</span>
</li>
</ul>
But my DayCtrl wants to know what day d it is, so has to pull that out of the scope:
app.controller('DayCtrl', function($scope){
$scope.date = $scope.d.date;
$scope.dayOfWeek =
['Mon','Tue','Wed','Thr','Fri','Sat','Sun']
[$scope.d.date.getDay()];
$scope.info = '... extra info...';
});
But this creates a dependency between the display and the controller. Ideally, I'd like to pass in d.date as an argument.
I could write a directive+controller and pass d.date in as an attribute. But that means I have to write a lot more and move the day's html into separate template, and I don't intend to use the DayCtrl elsewhere.
Alternatively, I could try and use <span ng-init="date=d.date"> but again, this feels dirty.
What's the right way of doing this.
Full example code on Plunker: http://plnkr.co/edit/wUxNFSEGjcDN7KlOLYdv which shows the problem I'm having with days and weeks.
To me, this seems like a job for a directive, with d.date specified as an attribute.
I don't know how info is populated, but potentially your directive would not need a controller.
The day's HTML doesn't have to be in a separate/directive template, it can remain in the HTML:
<li ng-repeat="d in days">
<day date="d.date">
{{dayOfWeek}} {{date}}: {{info}}
</day>
</li>
Directive:
app.directive('day', function() {
return {
restrict: 'E',
scope: { date: '=' },
link: function(scope) {
scope.dayOfWeek = ['Mon','Tue','Wed','Thr','Fri','Sat','Sun'][scope.date.getDay()];
scope.info = '... extra info...';
}
};
});
FYI, if you want to use ng-init, you can include it with the ng-controller:
<span ng-controller="DayCtrl" ng-init="date=d.date">