Reputation: 2515
When I call notificationService.showNotification("Test from controller")
from a controller the message in the directive's view is updated but when I then call notificationService.showNotification("Test from another service")
from another service the message in the directive's view doesn't get updated.
How should I do to always update currentNotification.message
in the directive's view when currentNotification
is updated in the notificationService?
Update:
The problem seems to occur when calling notificationService.showNotification("Test from another service")
from a setTimeout
function. See plunker: http://plnkr.co/edit/qD6OjamFjzOFbg43vj7R
Clicking on "Update from Other Service needs to be done twice for the message to update.
angular.module('myApp').service('notificationService',function() {
var notificationService = {
currentNotification : {
message: "",
},
showNotification : function(text){
this.currentNotification.message = text;
},
};
return notificationService;
});
angular.module('myApp').directive('notificationDirective', function(notificationService) {
return {
restrict: 'E',
replace: true,
scope: {
},
templateUrl: 'directive/notification-directive/notification-directive.html',
link: function(scope, element, attrs, fn) {
scope.currentNotification = notificationService.currentNotification;
}
};
});
directive/notification-directive/notification-directive.html:
<div>
<div ng-if="currentNotification.message.length > 0" id="notificationWrapper">
<div class="notification">
<div class="message">
{{currentNotification.message}}
</div>
</div>
</div>
</div>
Upvotes: 0
Views: 77
Reputation: 1891
You need to use $timeout which calls $scope.$apply, or you need to call $scope.$apply on your own :
myApp.controller('otherCtrl', function($scope, $timeout, notificationService, otherService) {
$scope.updateFromService = function() {
console.log("updateFromService");
$timeout(function(){
otherService.updateNotification();
}, 200);
};
});
Upvotes: 2