【发布时间】:2014-07-12 18:37:53
【问题描述】:
我了解 Angular 控制器应尽量不执行繁重的逻辑计算。
我的控制器中有一个函数,可以获取当前月份的 12 个月列表:
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;
}
});
并通过以下方式显示在我的 HTML 中:
<th ng-repeat="months in getLast12Months()">{[{ months }]}</th>
我尝试通过以下方式将其放入指令中:
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;
}
});
在 HTML 中:
<th ng-get-last-12-months>{[{ months }]}</th>
我可以看到我的指令是通过 console.log 触发的,但输出显示为:
["2014 年 5 月","2014 年 4 月","2014 年 3 月","2014 年 2 月","2014 年 1 月","2013 年 12 月","2013 年 11 月","2013 年 10 月","2013 年 9 月"," 2013 年 8 月","2013 年 7 月","2013 年 6 月"]
而不是 ng-repeat 时尚显示为:
2014 年 5 月 2014 年 4 月 2014 年 3 月 2014 年 2 月 2014 年 12 月 2013 年 11 月 2013 年 10 月 2013 年 9 月 2013 年 8 月 2013 年 7 月 2013 年 6 月
基于工程师示例的更新
但是看到:错误:[$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;
}
};
});
【问题讨论】:
-
你可能需要的是服务,而不是指令。
-
我猜有问题
-
@Skeptor - 你是对的,
导致了那个错误, 工作正常。但是,我需要它在中。
标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat