Angularjs 指令'中的变量;用户的视图并不总是更新
当我从控制器调用Angularjs 指令'中的变量;用户的视图并不总是更新,angularjs,angularjs-directive,Angularjs,Angularjs Directive,当我从控制器调用notificationService.showNotification(“从控制器测试”)时,指令视图中的消息会更新,但当我从另一个服务调用notificationService.showNotification(“从另一个服务测试”)时,指令视图中的消息不会更新 当notificationService中更新了currentNotification时,如何始终更新指令视图中的currentNotification.message 更新: 从setTimeout函数调用noti
notificationService.showNotification(“从控制器测试”)
时,指令视图中的消息会更新,但当我从另一个服务调用notificationService.showNotification(“从另一个服务测试”)
时,指令视图中的消息不会更新
当notificationService中更新了currentNotification
时,如何始终更新指令视图中的currentNotification.message
更新:
从setTimeout
函数调用notificationService.showNotification(“从另一个服务测试”)
时,似乎会出现此问题。见普朗克:
单击“需要从其他服务更新两次”以更新消息
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;
}
};
});
指令/通知指令/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>
{{currentNotification.message}
您需要使用$timeout调用$scope.$apply,或者您需要自己调用$scope.$apply:
myApp.controller('otherCtrl', function($scope, $timeout, notificationService, otherService) {
$scope.updateFromService = function() {
console.log("updateFromService");
$timeout(function(){
otherService.updateNotification();
}, 200);
};
});
您有plunker吗?您可以使用
$watch
,尝试将scope.currentNotification=notificationService.currentNotification
更改为scope.$watch(function(){return notificationService.currentNotification;},function(){scope.currentNotification=notificationService.currentNotification});
plunker: