Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 指令'中的变量;用户的视图并不总是更新_Angularjs_Angularjs Directive - Fatal编程技术网

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: