Currently, I am in the process of developing my inaugural AngularJS application and am faced with the challenge of a directive not updating its view when there are changes to the array received from the service.
Below is the structure of my directive:
angular.module('Aristotle').directive('ariNotificationCenter', function (Notifications) {
return {
replace: true,
restrict: 'E',
templateUrl: 'partials/ariNotificationCenter.html',
controller: function ($scope) {
$scope.notifications = Notifications.getNotifications();
$scope.countUnread = function () {
return Notifications.countUnread();
};
}
};
});
The partial contains:
<p>Unread count: {{countUnread()}}</p>
Now, let's take a look at my Notifications
service:
function Notification (text, link) {
this.text = text;
this.link = link;
this.read = false;
}
var Notifications = {
_notifications: [],
getNotifications: function () {
return this._notifications;
},
countUnread: function () {
var unreadCount = 0;
$.each(this._notifications, function (i, notification) {
!notification.read && ++unreadCount;
});
return unreadCount;
},
addNotification: function (notification) {
this._notifications.push(notification);
}
};
// Simulate notifications being periodically added
setInterval(function () {
Notifications.addNotification(new Notification(
'Something happened!',
'/#/somewhere',
Math.random() > 0.5
));
}, 2000);
angular.module('Aristotle').factory('Notifications', function () {
return Notifications;
});
The issue lies in the fact that the getNotifications
function returns a reference to the array, which undergoes changes due to the setInterval
. Unfortunately, the only way to update the view is by executing $scope.$apply()
, which eliminates the automation aspect of Angular.
I would greatly appreciate any guidance on what might be causing this problem.
Thank you.