我经常看到一些例子,如<calendar events="a.appointments"></calendar>
,其中控制器内分配的数据通过属性绑定传递给指令。处理AngularJS指令数据的推荐方式
下面的代码显示了一个替代解决方案,其中所需数据直接在指令link
函数中收集。使用这种方法不需要单独的控制器。
diary.html
<calendar></calendar>
calendar.js
angular.module('diary').
directive('calendar', ['AppointmentsService', function(AppointmentsService) {
return {
template: 'calendar.html',
scope: {},
link: function($scope) {
$scope.events = {};
AppointmentsService.getAppointments().then(function(result) {
$scope.events = result;
});
}
};
}]);
这是一个合适的或有缺陷的最终办法走?