Answer the question
In order to leave comments, you need to log in
How to make directives communicate with each other?
I'll spam the toaster in a couple of days.
There is a directive showing the list of read and unread messages. I would like to make another directive that will show an icon with the number of unread messages in the header. It is logical that this directive should depend on the first, but is not nested in the first. How do they communicate with each other? How do you know require: '^?myNotifications',
it won't fit?
The first directive that fetches data from the service:
angular
.module('app.notifications')
.directive('myNotifications', myNotifications);
function myNotifications() {
var directive = {
link: link,
templateUrl: 'app/notifications/views/show.client.notification.html',
restrict: 'EA',
controller: NotificationController,
controllerAs: 'notification'
};
return directive;
function link(scope, element, attrs) {
}
}
NotificationController.$inject = ['notificationService', '_'];
function NotificationController(notificationService, _) {
var vm = this;
vm.showNotificationList = false;
vm.unreadNotifications = [];
vm.readNotifications = [];
activate();
function activate() {
return getNotifications().then(function () {
SplitNotifications(vm.showNotificationList);
});
}
;
function getNotifications() {
return notificationService.getNotificationsData()
.$promise.then(function (data) {
vm.showNotificationList = data;
return vm.showNotificationList;
});
}
function SplitNotifications(showNotificationList) {
for (var i = 0; i < showNotificationList.length; i++) {
vm.unreadNotifications = _.filter(showNotificationList, {status: '1'});
vm.readNotifications = _.filter(showNotificationList, {status: '2'});
}
}
}
unreadNotifications
and read it length
and add it to above the icon:angular
.module('app.notifications')
.directive('myNotificationsBell', myNotificationsBell);
function myNotificationsBell() {
var directive = {
link: link,
require: '^?myNotifications',
template: ' <md-button aria-label="Open notification" class="md-icon-button" ng-click="$mdOpenMenu()">' +
'<md-icon md-svg-icon="notifications" ></md-icon><sup>3</sup>' +
'</md-button>',
restrict: 'EA',
controller: NotificationBellController,
controllerAs: 'bell'
};
return directive;
function link(scope, element, attrs) {
}
NotificationBellController.$inject = [];
function NotificationBellController() {
}
}
Answer the question
In order to leave comments, you need to log in
no, let these two directives depend on one service that provides this information.
Communication of directives is the place to be if one is nested in another or they have a real need to communicate. In your case, one directive asks the service to mark something as read, and the other simply monitors the number of unread and react to the change.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question