2017-06-14 63 views
2

我有事件从我服务的服务加载列表的diretive:

.directive('appointments', [function() { 
     return { 
      restrict: 'CE', 
      scope: { 
       ngTemplate: '=', 
      }, 
      controller: ['$scope','calendarService', function ($scope, calendarService) { 
       var vm = this; 
       vm.events = calendarService.getEvents(); 
      }], 
      controllerAS:'vm', 
      link: function (scope, elem, attrs) { 
       scope.getTemplateUrl = function() { 
        if (angular.isDefined(scope.ngTemplate)) 
         return scope.ngTemplate; 
        else 
        return "/list.directive.html"; 
       } 
      }, 
      template: '<div ng-include="getTemplateUrl()"></div>' 
     } 
    }]) 

现在在另一个指令我更新这份名单,我怎么可以更新第一个控制器列表?在第一个指令使用

此:

.directive('appointmentsUpdate', [function() { 
      return { 
       restrict: 'CE', 
       scope: { 
        ngEventId: '=', 
       }, 
       controller: ['$scope','calendarService', function ($scope, calendarService) { 
        var vm = this; 
        vm.update = calendarService.updateEvent(scope.ngEventId).then(function(res){ 


    // Here is where the newly created item, should be added to the List (vm.events) from first directive 

) 
}); 
       }], 
       controllerAS:'vm', 
       link: function (scope, elem, attrs) { 
        scope.getTemplateUrl = function() { 
         if (angular.isDefined(scope.ngTemplate)) 
          return scope.ngTemplate; 
         else 
         return "/list.directive.html"; 
        } 
       }, 
       template: '<div ng-include="getTemplateUrl()"></div>' 
      } 
     }]) 

回答

1

可以使用角广播服务

$rootScope.$broadcast('greeting', data_needs_to_be_send); 
其他指令

监听事件来更新其范围:

$scope.$on('greeting', listenGreeting) 

    function listenGreeting($event, message){ 
    alert(['Message received',message].join(' : ')); 
    } 
+0

这是正确的方法吗? –

+0

是的,你可以做到这一点,并将永远工作,因为它的一个角度特征。但它不仅是你可以使用service.but的方式,但它的超级容易实现。 –

+1

我认为这是两条指令之间沟通的正确途径。使用$ broadcast和$ emit将创建松散耦合的指令。我的建议是使用$ scope。$ broadcast,如果您的'appointmentmentsUpdate'指令是'约会'指令的子元素。 $ rootScope将把事件广播到应用程序中的所有子范围。 –

0

我们使用require道具在指令之间进行沟通。

像这样的事情

return { 
    restrict: 'AE', 
    require: '^ParentDirective or ^SameLevelDirective' 
} 

这里是Driectives That Communicate by ToddMotto

+0

能否请您提供一个基于上述代码的例子?我通读了文章并尝试了,但它不工作?! –

0

服务是单身了明确的解释,所以如果你从一个地方更新列表(与您calendarService.updateEvent()),然后如果你检索数据从其他指令中的服务中,它应该是更新的列表。 您可以使用手表来检查清单何时更新:

$scope.$watch(() => calendarService.getEvents(), (newValue, oldValue) => { 
    // update your scope with the new list 
}, true); 
相关问题