I understand that Angular controllers should try not to perform heavy logic calculations.
I have a function within my controller that gets a list of 12months from the current month:
app.controller("MyController", function($scope) {
$scope.getLast12Months = function () {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
for(var i = 0; i < 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
// Subtract a month each time
date.setMonth(date.getMonth() - 1);
}
$scope.months = months;
return months;
}
});
And displayed in my HTML via:
<th ng-repeat="months in getLast12Months()">{[{ months }]}</th>
Ive tried putting this into a directive via:
app.directive("ngGetLast12Months", function () {
return function ($scope) {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
for(var i = 0; i < 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
// Subtract a month each time
date.setMonth(date.getMonth() - 1);
}
$scope.months = months;
return months;
}
});
And in the HTML:
<th ng-get-last-12-months>{[{ months }]}</th>
I can see my directive is being triggered via a console.log, but the output is appearing as:
["May 2014","Apr 2014","Mar 2014","Feb 2014","Jan 2014","Dec 2013","Nov 2013","Oct 2013","Sep 2013","Aug 2013","Jul 2013","Jun 2013"]
Rather than the ng-repeat fashion displaying as:
May 2014 Apr 2014 Mar 2014 Feb 2014 Jan 2014 Dec 2013 Nov 2013 Oct 2013 Sep 2013 Aug 2013 Jul 2013 Jun 2013
UPDATE Based on Engineer's Example
However seeing: Error: [$compile:tplrt] errors.angularjs.org/1.2.8/$compile/…
app.directive('ngGetLast12Months', function () {
return {
replace: true,
restrict: 'EA',
template: '<th ng-repeat="month in months">{[{ month }]}</th>',
link: function ($scope) {
var date = new Date();
var months = [], monthNames = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
for (var i = 0; i < 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
// Subtract a month each time
date.setMonth(date.getMonth() - 1);
}
$scope.months = months;
return months;
}
};
});