我經常看到一些例子,如<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;
});
}
};
}]);
這是一個合適的或有缺陷的最終辦法走?