简体   繁体   English

angularjs最佳实践 - 没有$ rootScope的指令之间的通信?

[英]angularjs best practices - communication between directives without $rootScope?

So I have a nested directive that I need to communicate with a separate directive on the page (same controller). 所以我有一个嵌套的指令,我需要与页面上的单独指令(同一个控制器)进行通信。 I tried the isolate scope approach but given how nested the first directive is, I abandoned that approach. 我尝试了隔离范围方法,但考虑到第一个指令的嵌套方式,我放弃了这种方法。 I'm writing this code keeping in mind that $scope might not be around in 2.0. 我正在编写这段代码,请记住$scope可能不在2.0左右。 Is there an alternative solution to my approach that would fit with Angular Best practices? 我的方法是否有替代解决方案适合Angular Best实践?

Inside nested directive (3 levels deep): 嵌套指令内部(3级深):

$scope.chooseCard = function (selectedId) {
  this.data = 'init value';
  $rootScope.$emit('row chosen', selectedId);
  this.data = selectedId;
};

Inside directive #2 that needs data from the nested directive: 内部指令#2需要嵌套指令中的数据:

$rootScope.$on('row chosen', function (e, data) {
  ctrl.id = data;
  console.log("this is the IDDDDDD", ctrl.id);
  Service.func(ctrl.id);
});

$scope might not be around, but bindings sure will. $scope可能不在,但绑定肯定会。 You have two main options: 您有两个主要选择:

  1. Use a service and set this piece of data on there, then watch it in the child directive. 使用服务并在那里设置这段数据,然后在子指令中观察它。 This will work, but I do feel like it harms composition and re-use since you can no longer have multiple instances of the directive (they would all depend on the singleton service). 这将有效,但我觉得它会损害组合和重用,因为你不能再拥有该指令的多个实例(它们都将依赖于单例服务)。

  2. Use an isolate scope as you mentioned earlier and then watch the binding using an '&' expression. 如前所述使用隔离范围,然后使用“&”表达式观察绑定。 This will be the closest you're going to get to Angular2 without using something like ngForward since the flow of data from parent -> child is still the primary method of data-binding in Angular2. 这将是你最接近Angular2而不使用像ngForward这样的ngForward因为来自parent - > child的数据流仍然是Angular2中数据绑定的主要方法。 This is the preferred way to accomplish this imo even if it ends up being more verbose. 这是实现这个imo的首选方法,即使它最终变得更加冗长。

No matter what solution you choose, make sure that you don't leak memory; 无论您选择何种解决方案,请确保不泄漏内存; if you don't unbind that $rootScope.$on handler, then you will leak memory every time that an instance of the directive is created and subsequently destroyed. 如果你没有取消绑定$rootScope.$on handler,那么每次创建指令的实例并随后销毁时,你都会泄漏内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM