当我从控制器调用notificationService.showNotification("Test from controller")
时,指令视图中的消息会更新,但是当我从另一个服务调用notificationService.showNotification("Test from another service")
时,指令视图中的消息不会更新。
在notificationService中更新currentNotification.message
时,如何在指令视图中始终更新currentNotification
?
更新
从notificationService.showNotification("Test from another service")
函数调用setTimeout
时似乎发生了问题。见plunker:http://plnkr.co/edit/qD6OjamFjzOFbg43vj7R
单击“从其他服务更新需要完成两次以更新消息。
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.html:
<div>
<div ng-if="currentNotification.message.length > 0" id="notificationWrapper">
<div class="notification">
<div class="message">
{{currentNotification.message}}
</div>
</div>
</div>
</div>
答案 0 :(得分:2)
你需要使用$ timeout来调用$ scope。$ apply,或者你需要调用$ scope。$ apply你自己:
myApp.controller('otherCtrl', function($scope, $timeout, notificationService, otherService) {
$scope.updateFromService = function() {
console.log("updateFromService");
$timeout(function(){
otherService.updateNotification();
}, 200);
};
});